gpt4 book ai didi

java - 按多个字段对一组字符串、整数进行排序

转载 作者:行者123 更新时间:2023-11-29 04:24:09 25 4
gpt4 key购买 nike

有一个 Map 并尝试对 String 的值和长度进行排序。我试图比较语句中的两个不同的东西,所以不知道我是否需要两个不同的语句。这用于比较数字根,因此字符串长度和数字根是值和值。

例如:

("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)

但是 ("103",4) > ("4",4) 因为 "103"的长度 > "4", 而 ("11101",4) > ("103",4);, 长度 "11101"> "103"

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});

编辑对上述问题的回答(也给出了回复)

 Map<String,Integer> unsortMap = new.
TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
.sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.println(result);

最佳答案

If you already have a map, and you want to order it, by lenght key, and by value then:

Map<String,Integer> unsortMap = new TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4);

Map<String, Integer> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length))

).sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));


System.out.println(result);

out => {4=4, 103=4, 1003=4, 11101=4, 5=5}

关于java - 按多个字段对一组字符串、整数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47271481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com