我有一個List<Integer>帶有值集合的Java ,例如包含:
[0, 5, 2, 1, 3, 2, 6, 1, 1, 0, 10]
我想按每個元素的第一次出現對串列進行排序,并使用以下新排序的串列:
[0, 0, 5, 2, 2, 1, 1, 1, 3, 6, 10]
在List我處理將有最大400-500元,所以一些輕量級是首選,但我不能完全弄清楚的方法。
uj5u.com熱心網友回復:
您可以使用indexOf( 回傳串列中元素的第一個索引)的結果直接進行排序。
List<Integer> list = Arrays.asList(0, 5, 2, 1, 3, 2, 6, 1, 1, 0, 10);
list.sort(Comparator.comparingInt(list::indexOf));
System.out.println(list);
Demo
uj5u.com熱心網友回復:
我認為使用 LinkedHashMap 有更簡單的解決方案,它會記住放置順序:
List<Integer> source = Arrays.asList(0, 5, 2, 1, 3, 2, 6, 1, 1, 0, 10);
List<Integer> target = new ArrayList<>();
Map<Integer, Integer> map = new LinkedHashMap<>();
source.forEach(number -> map.merge(number, 1, Integer::sum));
map.forEach((key, value) -> {
for (int i = 0; i < value; i ) {
target.add(key);
}
});
System.out.println(target);
uj5u.com熱心網友回復:
您需要 2 個資料結構:
- 一個 Map 來存盤一個數字出現的次數
- 一個串列來記住它們發生的順序
此代碼執行您想要的操作:
String in = "0, 5, 2, 1, 3, 2, 6, 1, 1, 0, 10";
String[] split = in.split(", ");
List<Integer> lstIn = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
Map<Integer, Integer> theMap = new HashMap<>();
List<Integer> listOccurence = new LinkedList<>();
for(Integer i:lstIn) {
theMap.compute(i, (k,v)->v==null?1:v 1);
if(!listOccurence.contains(i)) {
listOccurence.add(i);
}
}
List<Integer> out = new LinkedList<>();
for(Integer i:listOccurence) {
Integer count = theMap.get(i);
for(int j=0;j<count;j ) {
out.add(i);
}
}
System.out.println(out);
這列印:
[0, 0, 5, 2, 2, 1, 1, 1, 3, 6, 10]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351251.html
