java 排序工具類 滿足基本開發需求

排序工具類

@Data
@AllArgsConstructor
@ToString
public class Student {
    private Long id;

    private String name;

    private Integer score;
}
  • List 排序
/**
 * List排序
 */
public class ListSortExample {

    private List<Student> studentList = Lists.newArrayList();

    @Before
    public void init(){
        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));
    }

    /**
     * 逆序排序規則
     */
    @Test
    public void testSortWithStream(){

        /*使用Java8 Stream order*/
        List<Student> 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<Student> sortedList1 = studentList.stream().sorted(Comparator.comparing(Student::getScore).thenComparing(Student::getName).reversed()).collect(Collectors.toList());
        System.out.println(sortedList1);
    }

    /**
     * 多字段排序---方式一
     */
    @Test
    public void testSort(){
        Comparator<Student> compareByScoreAndNameReverse = Comparator.comparing(Student::getScore).thenComparing(Student::getName);
        studentList.sort(compareByScoreAndNameReverse);
        System.out.println(studentList);
    }

    /**
     * 多字段排序---方式二
     */
    @Test
    public void testSort1(){
        Comparator<Student> compareByScoreAndNameReverse = Comparator.comparing(Student::getScore).thenComparing(Student::getName);
        Collections.sort(studentList, compareByScoreAndNameReverse);
        System.out.println(studentList);
    }

    /**
     * 自定義排序
     */
    @Test
    public void  customSort (){
        final  List<String> sortList =  Arrays.asList("Alice","Michael","Jane","zhuoli");
        List<Student> result = studentList.stream().sorted(Comparator.comparing(Student::getName, (x, y) -> {
            for(String sort : sortList){
                if(sort.equals(x) || sort.equals(y)){
                    if(x.equals(y)){
                        return 0;
                    }else if(sort.equals(x)){
                        return -1;
                    }else{
                        return 1;
                    }
                }
            }
            return 0;
        })).collect(Collectors.toList());
        System.out.println(result);
    }
}
  • Map排序
/**
 * Map排序
 */
public class SortByKeyExample {
    @Test
    public void SortByKeyTest() {
        Map<String, Integer> 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<String, Integer> 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<String, Integer> 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);
    }
}```

```java
/**
 * Map排序
 */
public class SortByValueExample {
    @Test
    public void sortByCommonValue() {
        Map<String, Integer> 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<String, Integer> 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<String, Integer> result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

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

    @Test
    public void sortedByObjectValueExample(){
        List<Student> 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<Long, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getId, ele -> ele));

        //sort value by student score
        Map<Long, Student> 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 排序

public class SetSortExample {
    private Set<Student> studentSet = Sets.newHashSet();

    @Before
    public void init(){
        studentSet.add(new Student(1001L, "zhuoli", 99));
        studentSet.add(new Student(999L, "Alice", 87));
        studentSet.add(new Student(1345L, "Michael", 90));
        studentSet.add(new Student(1024L, "Jane", 99));
    }

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

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

代碼已傳github,點擊跳轉

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章