JAVA找出List集合中重複次數最多的資料和次數
阿新 • • 發佈:2018-11-08
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Test1 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); list.add(99); list.add(77); list.add(99); list.add(11); list.add(33); list.add(99); list.add(55); list.add(929); list.add(919); list.add(88); list.add(00); list.add(123); list.add(223); list.add(567); list.add(77); list.add(77); // list.add(77); // list.add(77); // list.add(77); int count = 0; //重複的加入list2集合 for (int i = 0; i < list.size(); i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i).equals(list.get(j))) { list2.add(list.get(i)); break; } } } //統計list2集合中重複資料出現次數,對應放入Map集合 for (Integer obj : list2) { if (map.containsKey(obj)) { count++; map.put(obj, map.get(obj).intValue() + 1); } else { map.put(obj, 1); } } System.out.println("count=" + count); list2.clear(); //迭代Map集合,重複資料出現最多的加入list3集合 Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, Integer> entry = it.next(); if (entry.getValue() == count) { list2.add(entry.getKey()); // System.out.println("key=" + entry.getKey() + "," + "value=" + entry.getValue()); } } if (list2.size() > 1) { System.out.println(list2 + "出現的次數一樣多,一共出現了:" + (count + 1) + "次"); } if (list2.size() == 1) { System.out.println("出現最多次數的是:" + list2 + ",總共出現了:" + (count + 1) + "次"); } } }