如何对List<Pair<A, List<B>>>的数据进行排序处理
时间: 2023-11-16 07:07:07 浏览: 160
可以使用Java中的Collections.sort()方法对List<Pair<A, List<B>>>进行排序处理。在排序时,可以使用Comparator接口的实现类来指定排序规则。
例如,假设我们要对一个List<Pair<String, List<Integer>>>按照每个Pair中List<Integer>的最大值进行排序,可以按照以下步骤进行:
1. 创建一个实现了Comparator<Pair<String, List<Integer>>>接口的类,实现compare方法,比较每个Pair中List<Integer>的最大值。
```
class PairComparator implements Comparator<Pair<String, List<Integer>>> {
@Override
public int compare(Pair<String, List<Integer>> o1, Pair<String, List<Integer>> o2) {
int max1 = Collections.max(o1.getValue());
int max2 = Collections.max(o2.getValue());
return Integer.compare(max1, max2);
}
}
```
2. 调用Collections.sort()方法,并传入List<Pair<String, List<Integer>>>和PairComparator实例作为参数。
```
List<Pair<String, List<Integer>>> pairs = new ArrayList<>();
pairs.add(new Pair<>("Pair1", Arrays.asList(1, 2, 3)));
pairs.add(new Pair<>("Pair2", Arrays.asList(4, 5, 6, 7)));
pairs.add(new Pair<>("Pair3", Arrays.asList(2, 9, 8)));
Collections.sort(pairs, new PairComparator());
for (Pair<String, List<Integer>> pair : pairs) {
System.out.println(pair.getKey() + ": " + pair.getValue());
}
```
输出结果为:
```
Pair1: [1, 2, 3]
Pair3: [2, 9, 8]
Pair2: [4, 5, 6, 7]
```
阅读全文
相关推荐

















