您好我已经创建了一个逻辑来计算数组列表中的重复项,但它不是按照我想要的确切顺序打印。下面我提供了我的代码和我的要求。
我需要以下格式,
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
但是,我的格式正在以下,
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
这是我的代码
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));
}
}
}
答案 0 :(得分:2)
使用LinkedHashMap
维护广告订单,而不是HashMap
:
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);
}