我使用java lambda对列表进行排序。

我怎么能逆向排序呢?

我看到了这篇文章,但我想使用java 8 lambda。

这是我的代码(我使用* -1)作为一个黑客

Arrays.asList(files).stream()
    .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
    .sorted(new Comparator<File>() {
        public int compare(File o1, File o2) {
            int answer;
            if (o1.lastModified() == o2.lastModified()) {
                answer = 0;
            } else if (o1.lastModified() > o2.lastModified()) {
                answer = 1;
            } else {
                answer = -1;
            }
            return -1 * answer;
        }
    })
    .skip(numOfNewestToLeave)
    .forEach(item -> item.delete());

当前回答

    //sort Stream in reverse oreder with using Lambda Expressrion.

    List<String> list = Arrays.asList("Ram","Rahul","Ravi","Vishal","Vaibhav","Rohit","Harit","Raghav","Shubhan");
    List<String> sortedListLambda = list.stream().sorted((x,y)->y.compareTo(x)).collect(Collectors.toList());
    System.out.println(sortedListLambda);

其他回答

Use

Comparator<File> comparator = Comparator.comparing(File::lastModified); 
Collections.sort(list, comparator.reversed());

然后

.forEach(item -> item.delete());

你可以像这样用自己的逻辑定义比较器;

private static final Comparator<UserResource> sortByLastLogin = (c1, c2) -> {
    if (Objects.isNull(c1.getLastLoggedin())) {
        return -1;
    } else if (Objects.isNull(c2.getLastLoggedin())) {
        return 1;
    }
    return c1.getLastLoggedin().compareTo(c2.getLastLoggedin());
};   

并在foreach中使用它:

list.stream()
     .sorted(sortCredentialsByLastLogin.reversed())
     .collect(Collectors.toList());

可供选择的共享方式:

ASC

List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName)).collect(Collectors.toList());

DESC

List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName).reversed()).collect(Collectors.toList());

如果你想按对象的日期类型属性排序,那么

public class Visit implements Serializable, Comparable<Visit>{
private static final long serialVersionUID = 4976278839883192037L;

private Date dos;

public Date getDos() {
    return dos;
}

public void setDos(Date dos) {
    this.dos = dos;
}

@Override
public int compareTo(Visit visit) {
    return this.getDos().compareTo(visit.getDos());
}

}

List<Visit> visits = getResults();//Method making the list
Collections.sort(visits, Collections.reverseOrder());//Reverser order

对于反向排序,只需改变x1, x2的顺序来调用x1. compareto (x2)方法,结果将彼此反向

默认的顺序

List<String> sortedByName = citiesName.stream().sorted((s1,s2)->s1.compareTo(s2)).collect(Collectors.toList());
System.out.println("Sorted by Name : "+ sortedByName);

相反的顺序

List<String> reverseSortedByName = citiesName.stream().sorted((s1,s2)->s2.compareTo(s1)).collect(Collectors.toList());
System.out.println("Reverse Sorted by Name : "+ reverseSortedByName );