Java8实现Map/List/Set排序

Java8之前如果想对一个集合排序,那么集合元素要么实现了Comparable接口,要么另外定义一个继承于Comparator的比较器并实现compare方法,使用起来是非常麻烦的。在我之前的文章中也介绍了一种Guava的排序实现方案,也是非常简单的,有兴趣的同学可以去了解一下Guava Ordering 。Java8之后可以使用java.util包的Comparator比较器,实现对集合的排序,使用起来非常简单。

首先定义一个实体类:

@Getter
@Setter
@AllArgsConstructor
@ToString
public class Student {
    private Long id;

    private String name;

    private Integer score;
}
  • List排序

使用Stream对List进行排序:

@Test
public void testSortWithStream(){

    /*使用Java8 Stream order*/
    List sortedList = studentList.stream().sorted(Comparator.comparing(Student::getScore).reversed()).collect(Collectors.toList());
    System.out.println(studentList);
    System.out.println(sortedList);

    /*使用Java8 Stream order按照score、name逆序排序*/
    List sortedList1 = studentList.stream().sorted(Comparator.comparing(Student::getScore).thenComparing(Student::getName).reversed()).collect(Collectors.toList());
    System.out.println(sortedList1);
}

使用list的sort方法排序:

@Test
public void testSort(){
    Comparator compareByScoreAndNameReverse = Comparator.comparing(Student::getScore).thenComparing(Student::getName).reversed();
    studentList.sort(compareByScoreAndNameReverse);
    System.out.println(studentList);
}

还有一种不推荐使用的方法,Collections.sort():

@Test
public void testSort1(){
    Comparator compareByScoreAndNameReverse = Comparator.comparing(Student::getScore).thenComparing(Student::getName).reversed();
    Collections.sort(studentList, compareByScoreAndNameReverse);
    System.out.println(studentList);
}
  • Map排序

根据key对Map排序:

@Test
public void SortByKeyTest() {
    Map unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    unsortMap.put("c", 20);
    unsortMap.put("d", 1);
    unsortMap.put("e", 7);
    unsortMap.put("y", 8);
    unsortMap.put("n", 99);
    unsortMap.put("g", 50);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    System.out.println("Original...");
    System.out.println(unsortMap);

    // sort by keys, a,b,c..., and return a new LinkedHashMap
    // toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
    Map result = unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    //Alternative way to sort a Map by keys, and put it into the "result" map
    Map result2 = new LinkedHashMap<>();
    unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

    System.out.println("Sorted...");
    System.out.println(result);
    System.out.println(result2);
}

根据value对Map进行排序:

@Test
public void sortByCommonValue() {
    Map unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    unsortMap.put("c", 20);
    unsortMap.put("d", 1);
    unsortMap.put("e", 7);
    unsortMap.put("y", 8);
    unsortMap.put("n", 99);
    unsortMap.put("g", 50);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    System.out.println("Original...");
    System.out.println(unsortMap);

    //sort by values, and reserve it, 10,9,8,7,6...
    Map result = unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    
    //Alternative way
    Map result2 = new LinkedHashMap<>();
    unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue().reversed())
            .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

    System.out.println("Sorted...");
    System.out.println(result);
    System.out.println(result2);
}

如果value是自定义对象,使用某个成员变量进行排序:

@Test
public void sortedByObjectValueExample(){
    List studentList = Lists.newArrayList();
    studentList.add(new Student(1001L, "zhuoli", 99));
    studentList.add(new Student(999L, "Alice", 87));
    studentList.add(new Student(1345L, "Michael", 90));
    studentList.add(new Student(1024L, "Jane", 99));

    //List -> Map
    Map studentMap = studentList.stream().collect(Collectors.toMap(Student::getId, ele -> ele));

    //sort value by student score
    Map result = studentMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.comparing(Student::getScore).reversed()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    System.out.println(result);
}
  • Set排序

@Test
public void setSortTest(){
    /*使用Java8 Stream order,结果转List*/
    List sortedList = studentSet.stream().sorted(Comparator.comparing(Student::getScore).reversed()).collect(Collectors.toList());
    System.out.println(sortedList);

    /*使用Java8 Stream order,使用LinkedHashSet保持顺序*/
    LinkedHashSet sortedSet1 = Sets.newLinkedHashSet();
    studentSet.stream().sorted(Comparator.comparing(Student::getScore).reversed()).forEachOrdered(sortedSet1::add);
    System.out.println(sortedSet1);
}

示例代码:码云 – 卓立 – Java8集合排序

你可能感兴趣的:(Java,Java,基础,Java8)