How to count duplicates in ArrayList<Integer> in the exact order they are coming using java
本问题已经有最佳答案,请猛点这里访问。
嗨,我创建了一个逻辑来计算数组列表中的重复项,但它没有按我想要的确切顺序打印。下面我提供了我的代码和要求。
我需要以下格式,
1 2 3 4 5 6 7 | list: [1, 1, 5, 3, 7, 3, 11, 2, 3, 1] number: 1, count: 3 number: 5, count: 1 number: 3, count: 3 number: 7, count: 1 number: 11, count: 1 number: 2, count: 1 |
但是,我的格式是:
1 2 3 4 5 6 7 | list: [1, 1, 5, 3, 7, 3, 11, 2, 3, 1] number: 1, count: 3 number: 2, count: 1 number: 3, count: 3 number: 5, count: 1 number: 7, count: 1 number: 11, count: 1 |
这是我的密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package com.abc; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyArrayListSort { public static void main(String []args){ new MyArrayListSort().start(); } public void start() { List<Integer> list = getList(1, 1, 5, 3, 7, 3, 11, 2, 3, 1); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer i : list) { Integer retrievedValue = map.get(i); if (null == retrievedValue) { map.put(i, 1); } else { map.put(i, retrievedValue + 1); } } System.out.println("list:" + list); printCount(map); } private List<Integer> getList(int... numbers) { List<Integer> list = new ArrayList<Integer>(); for (int i : numbers) { list.add(i); } return list; } private void printCount(Map<Integer, Integer> map) { for (Integer key : map.keySet()) { System.out.println("number:" + key +", count:" + map.get(key)); } } } |
使用保持插入顺序的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public void start() { List<Integer> list = getList(1, 1, 5, 3, 7, 3, 11, 2, 3, 1); Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); for (Integer i : list) { Integer retrievedValue = map.get(i); if (null == retrievedValue) { map.put(i, 1); } else { map.put(i, retrievedValue + 1); } } System.out.println("list:" + list); printCount(map); } |