我想按值长度对Map进行排序。例如,我有以下代码:
public static void main(String[] args) {
Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
Random random = new Random();
for (int i = 0; i < 5; i++) {
Map<Integer, Integer> mapA = new HashMap<>();
for (int j = 0; j < random.nextInt(10); j++) {
mapA.put(j, j);
}
map.put(i, mapA);
}
for (Map.Entry<Integer, Map<Integer, Integer>> entry:
map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}结果是:
0: {0=0, 1=1, 2=2, 3=3, 4=4, 5=5}
1: {}
2: {0=0, 1=1, 2=2, 3=3}
3: {0=0, 1=1, 2=2, 3=3}
4: {0=0, 1=1, 2=2}因此,我想要做的是按照值长度对这个Map进行排序,这样它返回:
1: {}
4: {0=0, 1=1, 2=2}
2: {0=0, 1=1, 2=2, 3=3}
3: {0=0, 1=1, 2=2, 3=3}
0: {0=0, 1=1, 2=2, 3=3, 4=4, 5=5}发布于 2022-05-06 15:24:22
您可以使用流来执行此操作:
var sorted = map.entrySet().stream().sorted(Comparator.comparingInt(it -> it.getValue().size())).toList();简单地说,您只需要一个定制的Comparator,它将得到一个Map.Entry的值,并比较这个值的size(),在您的例子中,这个值是另一个Map。
以下是完整的应用程序:
import java.util.*;
public class Application {
public static void main(String[] args) {
Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
Random random = new Random();
for (int i = 0; i < 5; i++) {
Map<Integer, Integer> mapA = new HashMap<>();
for (int j = 0; j < random.nextInt(10); j++) {
mapA.put(j, j);
}
map.put(i, mapA);
}
for (Map.Entry<Integer, Map<Integer, Integer>> entry:
map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
var sorted = map.entrySet().stream().sorted(Comparator.comparingInt(it -> it.getValue().size())).toList();
System.out.println(sorted);
}
}预期产出:
0: {0=0, 1=1}
1: {0=0, 1=1, 2=2, 3=3, 4=4}
2: {}
3: {0=0}
4: {0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7}
[2={}, 3={0=0}, 0={0=0, 1=1}, 1={0=0, 1=1, 2=2, 3=3, 4=4}, 4={0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7}]很明显,精确的输出取决于随机输入.
https://stackoverflow.com/questions/72143740
复制相似问题