Map集合小案例练习计算数组中每个元素个数
package Maptest01; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * FileName: MapDemo03 * Author: lps * Date: 2022/4/15 11:08 * Sign:刘品水 Q:1944900433 * 统计投票人数 */ public class MapDemo03 { public static void main(String[] args) { //1.吧八十个学生数据拿进来 String[] selects= {"A","B","C","D"}; StringBuilder sb = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 80; i++) { sb.append(selects[r.nextInt(selects.length)]); } System.out.println(sb); //2.定义map集合记录统计的结果 Map<Character,Integer> infos=new HashMap<>();//{} //3.遍历学生选择的数据 for (int i = 0; i < sb.length(); i++) { //4.提取当前选择的字符 char ch = sb.charAt(i); //5.判断Map集合中是否存在这个键 if (infos.containsKey(ch)){ //让其值+1 infos.put(ch,infos.get(ch)+1); }else { //说明此是第一次 infos.put(ch,1); } } infos.forEach((k,v)-> System.out.println(k+","+v)); } }