List<E> 、Set<E>和Map<K,E>的简单应用
题目一:
创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。
代码:
List_Test.java
1 /** 2 * 利用List<E>和Set<E>,求交集和并集; 3 */ 4 package cn.edu.ccut1; 5 import java.util.*; 6 7 public class Test_List { 8 9 public static void main(String[] args) { 10 ArrayList<String> L1 = new ArrayList<String>(); 11 ArrayList<String> L2 = new ArrayList<String>(); 12 L1.add("chen"); 13 L1.add("wang"); 14 L1.add("liu"); 15 L1.add("zhang"); 16 L2.add("chen"); 17 L2.add("Hu"); 18 L2.add("zhang"); 19 ArrayList<String> Jj = new ArrayList<String>(); 20 Jj.addAll(L1); 21 Jj.retainAll(L2); //将Jj中与L2中不相同的元素全部剔除; 22 System.out.println("交集是:"+Jj.toString()); 23 HashSet<String> Bj = new HashSet<String>(); 24 Bj.addAll(L1); 25 Bj.addAll(L2); //利用Set<E>唯一性的特点去除重复的元素取得并集; 26 System.out.println("并集是:"+Bj.toString()); 27 } 28 }
运行结果:
题目二:
编写一个应用程序,输入一个字符串,该串至少由数字、大写字母和小写字母三种字符中的一种构成,如“123”、“a23”、“56aD”、“DLd”、“wq”、“SSS”、“4NA20”,对输入内容进行分析,统计每一种字符的个数,并将该个数和每种字符分别输出显示。如:输入内容为“34Ah5yWj”,则输出结果为:数字——共3个,分别为3,4,5;小写字母——共3个,分别为h,y,j;大写字母——共2个,分别为A,W。
代码:
Map_Test.java
1 package cn.edu.ccut2; 2 import java.util.*; 3 4 public class Map_Test { 5 6 public static void main(String[] args) { 7 System.out.println("请输入一个字符串:"); 8 HashMap<String, String> M = new HashMap<String, String>(); 9 Scanner r = new Scanner(System.in); 10 String str = r.nextLine(); 11 int length = str.length(); 12 String c; 13 int count_num = 0; //统计数字,小写字母,大写字母的个数; 14 int count_A = 0; 15 int count_a = 0; 16 for(int i = 0 ; i < length ; i++){ 17 c = str.substring(i, i+1); 18 if(c.matches("\\d")){//判断是否为数字; 19 if(M.get("数字")==null){ 20 M.put("数字", c); 21 } 22 else{ 23 M.put("数字", M.get("数字")+","+c); 24 } 25 count_num++; 26 } 27 if(c.matches("[a-z]")){//判断是否为小写字母; 28 if(M.get("小写字母")==null){ 29 M.put("小写字母", c); 30 } 31 else{ 32 M.put("小写字母", M.get("小写字母")+","+c); 33 } 34 count_a++; 35 } 36 if(c.matches("[A-Z]")){//判断是否为大写字母; 37 if(M.get("大写字母")==null){ 38 M.put("大写字母", c); 39 } 40 else{ 41 M.put("大写字母", M.get("大写字母")+","+c); 42 } 43 count_A++; 44 } 45 } 46 Set set = M.entrySet(); //返回包含映射中项的集合; 47 Iterator it = set.iterator(); //获取迭代对象; 48 while(it.hasNext()){ 49 Map.Entry me = (Map.Entry)it.next(); 50 System.out.print(me.getKey()); 51 if(me.getKey().equals("数字")){ 52 System.out.print("——共"+count_num+"个,"); 53 }else if(me.getKey().equals("小写字母")){ 54 System.out.print("——共"+count_a+"个,"); 55 }else if(me.getKey().equals("大写字母")){ 56 System.out.print("——共"+count_A+"个,"); 57 } 58 System.out.println("分别为"+me.getValue()); 59 } 60 } 61 }
运行结果: