How to use a Java8 lambda to sort a stream in reverse order?

后端 未结 12 1695
暗喜
暗喜 2020-11-29 17:25

I\'m using java lambda to sort a list.

how can I sort it in a reverse way?

I saw this post, but I want to use java 8 lambda.

Here is my code (I used

12条回答
  •  时光说笑
    2020-11-29 18:03

    Sort file list with java 8 Collections

    Example how to use Collections and Comparator Java 8 to sort a File list.

    import java.io.File;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class ShortFile {
    
        public static void main(String[] args) {
            List fileList = new ArrayList<>();
            fileList.add(new File("infoSE-201904270100.txt"));
            fileList.add(new File("infoSE-201904280301.txt"));
            fileList.add(new File("infoSE-201904280101.txt"));
            fileList.add(new File("infoSE-201904270101.txt"));
    
            fileList.forEach(x -> System.out.println(x.getName()));
            Collections.sort(fileList, Comparator.comparing(File::getName).reversed());
            System.out.println("===========================================");
            fileList.forEach(x -> System.out.println(x.getName()));
        }
    }
    

提交回复
热议问题