JAVA 基础 day-18 练习

  1. 定义方法统计集合中指定元素出现的次数

    public static void main(String[] args) {
    		//定义方法统计集合中指定元素出现的次数,如"a" 3,"b" 2,"c" 1
    		List<String> list = new ArrayList<>();
    		
    		list.add("a");
    		list.add("a");
    		list.add("a");
    		list.add("b");
    		list.add("b");
    		list.add("c");
    		list.add("d");
    		list.add("d");
    		list.add("d");
    		list.add("d");
    		list.add("d");
    		int count = func_1(list, "a");
    		System.out.println(count);
    		int count1 = func_1(list, "b");
    		System.out.println(count1);
    		int count2 = func_1(list, "c");
    		System.out.println(count2);
    		int count3 = func_1(list, "d");
    		System.out.println(count3);
    	}
    	
    	public static int func_1(List<String> list, String key) {
    		int count = 0;
    		//foreach 遍历
    		for (String s : list) {
    			if (s.equals(key)) {
    				count++;
    			}
    		}
    		//iterator遍历
    //		Iterator<String> it = list.iterator();
    //		while (it.hasNext()) {
    //			if (it.next().equals(key)) {
    //				count++;
    //			}
    //		}
    		return count;
    	}


  2. 要求对集合中添加的元素排序

    	public static void main(String[] args) {
    
    		List<String> list = new ArrayList<>();
    		list.add("b");
    		list.add("f");
    		list.add("e");
    		list.add("c");
    		list.add("a");
    		list.add("d");
    		sort(list);
    		System.out.println(list);	// a, b, c, d, e, f
    
    	}
    	
    	private static void sort(List<String> list) {
    		String temp = "";
    		for (int i = 0; i < list.size(); i++) {
    			for(int j=i+1; j<list.size(); j++) {
    				if(list.get(i).toCharArray()[0] > list.get(j).toCharArray()[0]) {
    					temp = list.get(i);
    					list.set(i, list.get(j));
    					list.set(j, temp);
    				}
    			}
    		}
    		
    //		char[] String.toCharArray() 将此字符串转换为一个新的字符数组。
            
    		
    	}


猜你喜欢

转载自blog.csdn.net/alexzt/article/details/79758603