程序最终输出结果为:“a = 1,b = 2,c = 2,d = 1

定义一个泛型为String类型的List集合,统计该集合中每个字符(注意,不是字符串)出现的次数。例如:

  • 集合中有”abc”、”bcd”两个元素,程序最终输出结果为:“a = 1,b = 2,c = 2,d = 1”。
  • @author Administrator

*/

public class List {
public static void main(String[] args) {
// 创建集合对象
ArrayList list = new ArrayList<>();
list.add(“abc”);
list.add(“bcd”);

	// 将集合中的两个元素进行拼接
	String str = list.get(0) + list.get(1);
	methodl(str);
}

private static void methodl(String str) {
	HashMap<Character, Integer> map = new HashMap<>();
	for (char c : str.toCharArray()) {
		map.put(c, map.containsKey(c) ? map.get(c) + 1 : 1);
	}
	// 获取最后一个key
	Set<Character> chrs = map.keySet();
	ArrayList<Character> list = new ArrayList<Character>(chrs);
	char lastKey = (char) (list.get(list.size() - 1));
	for (Map.Entry<Character, Integer> entry : map.entrySet()) {
		char key = entry.getKey();
		int value = entry.getValue();
		// 如果是最后一个key直接打印key与value结束.
		if (key == lastKey) {
			System.out.println(key + "=" + value);
			break;
		}
		// 如果不是最后一个,打印 key与value和一个逗号分隔
		System.out.print(key + "=" + value + ",");
	}
}

}

猜你喜欢

转载自blog.csdn.net/Javastudenthhhk/article/details/89397148