avatar
童琦杰
Jul 21, 2019Technology

JAVA - 排序、分组

首先创建一个比较类,定义三种不同类型的字段,下面分别对其进行排序操作。

java
public class ComparableObject {
    private int intValue;
    private String stringValue;
    private DateTime timeValue;
    // constructors, getters and setters
}

初始化数据集合。

java
List<ComparableObject> objects = new ArrayList<>();
objects.add(new ComparableObject(1, "ddd", new DateTime(2019, 07,20)));
objects.add(new ComparableObject(3, "eee", new DateTime(2019, 07, 19)));
objects.add(new ComparableObject(2, "ccc", new DateTime(2019, 07, 23)));

分别根据字段intValuestringValuetimeValue进行正向排序和反向排序。

java
objects.stream().sorted(Comparator.comparing(ComparableObject::getIntValue)).collect(Collectors.toList());
objects.stream().sorted(Comparator.comparing(ComparableObject::getIntValue).reversed()).collect(Collectors.toList());
objects.stream().sorted(Comparator.comparing(ComparableObject::getStringValue)).collect(Collectors.toList());
objects.stream().sorted(Comparator.comparing(ComparableObject::getStringValue).reversed()).collect(Collectors.toList());
objects.stream().sorted(Comparator.comparing(ComparableObject::getTimeValue)).collect(Collectors.toList());
objects.stream().sorted(Comparator.comparing(ComparableObject::getTimeValue).reversed()).collect(Collectors.toList());

使用Lambda表达式排序。

java
objects.stream().sorted(Comparator.comparing(x -> x.getTimeValue().getTimestamp())).collect(Collectors.toList()); // 正序排序
objects.stream().sorted((x, y) -> (int)(x.getTimeValue().getTimestamp() - y.getTimeValue().getTimestamp())).collect(Collectors.toList()); // 正序排序
objects.stream().sorted((x, y) -> (int)(y.getTimeValue().getTimestamp() - x.getTimeValue().getTimestamp())).collect(Collectors.toList()); // 反序排序

多个字段排序。

java
Comparator<ComparableObject> a = Comparator.comparing(x -> x.getIntValue(), Comparator.reverseOrder());
Comparator<ComparableObject> b = a.thenComparing(x -> x.getStringValue().toUpperCase(), Comparator.reverseOrder());
Comparator<ComparableObject> c = b.thenComparing(x -> x.getTimeValue().getTimestamp(), Comparator.reverseOrder());
objects.stream().sorted(c).collect(Collectors.toList());

单个字段分组

java
Map<Integer, List<ComparableObject>> groups = objects.stream().collect(Collectors.groupingBy(x -> x.getTimeValue().getDay()));

for (Map.Entry<Integer, List<ComparableObject>> kv : groups.entrySet()) {
    System.out.println(String.format("%d\t%d", kv.getKey(), kv.getValue().size()));
}

多个字段分组

java
Function<ComparableObject, List<Object>> keyExtractor = obj -> Arrays.asList(obj.getIntValue(), obj.getStringValue());
Map<List<Object>, List<ComparableObject>> groups = objects.stream().collect(Collectors.groupingBy(keyExtractor));

for (Map.Entry<List<Object>, List<ComparableObject>> kv : groups.entrySet()) {
    System.out.println(String.format("%s\t%s\t%d", kv.getKey().get(0).toString(), kv.getKey().get(1).toString(), kv.getValue().size()));
}
© 2015-2022 tongqijie.com 版权所有沪ICP备17000682号