[英]How to use a Java8 lambda to sort a stream in reverse order?
I'm using java lambda to sort a list.我正在使用 java lambda 对列表进行排序。
how can I sort it in a reverse way?我怎样才能以相反的方式对其进行排序?
I saw this post , but I want to use java 8 lambda.我看到了这篇文章,但我想使用 java 8 lambda。
Here is my code (I used * -1) as a hack这是我的代码(我使用 * -1)作为 hack
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());
You can adapt the solution you linked in How to sort ArrayList<Long> in Java in decreasing order?您可以调整您在如何以降序对 Java 中的 ArrayList<Long> 进行排序中链接的解决方案? by wrapping it in a lambda:通过将其包装在 lambda 中:
.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())
note that f2 is the first argument of Long.compare
, not the second, so the result will be reversed.请注意, f2是Long.compare
的第一个参数,而不是第二个,因此结果将相反。
If your stream elements implements Comparable
then the solution becomes simpler:如果您的流元素实现了Comparable
那么解决方案就会变得更简单:
...stream()
.sorted(Comparator.reverseOrder())
Use采用
Comparator<File> comparator = Comparator.comparing(File::lastModified);
Collections.sort(list, comparator.reversed());
Then然后
.forEach(item -> item.delete());
You can use a method reference:您可以使用方法参考:
import static java.util.Comparator.*;
import static java.util.stream.Collectors.*;
Arrays.asList(files).stream()
.filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
.sorted(comparing(File::lastModified).reversed())
.skip(numOfNewestToLeave)
.forEach(item -> item.delete());
In alternative of method reference you can use a lambda expression, so the argument of comparing become:作为方法引用的替代方案,您可以使用 lambda 表达式,因此比较的参数变为:
.sorted(comparing(file -> file.lastModified()).reversed());
Alternative way sharing:替代方式分享:
ASC 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());
In simple, using Comparator and Collection you can sort like below in reversal order using JAVA 8简单地说,使用 Comparator 和 Collection,您可以使用JAVA 8按相反顺序进行如下排序
import java.util.Comparator;;
import java.util.stream.Collectors;
Arrays.asList(files).stream()
.sorted(Comparator.comparing(File::getLastModified).reversed())
.collect(Collectors.toList());
This can easily be done using Java 8 and the use of a reversed Comparator .这可以使用 Java 8 和反向Comparator轻松完成。
I have created a list of files from a directory, which I display unsorted, sorted and reverse sorted using a simple Comparator for the sort and then calling reversed() on it to get the reversed version of that Comparator.我从一个目录中创建了一个文件列表,我使用一个简单的比较器进行排序显示未排序、排序和反向排序,然后对其调用 reversed() 以获取该比较器的反向版本。
See code below:见下面的代码:
package test;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
public static void main(String... args) {
File directory = new File("C:/Media");
File[] files = directory.listFiles();
List<File> filesList = Arrays.asList(files);
Comparator<File> comparator = Comparator.comparingLong(File::lastModified);
Comparator<File> reverseComparator = comparator.reversed();
List<File> forwardOrder = filesList.stream().sorted(comparator).collect(Collectors.toList());
List<File> reverseOrder = filesList.stream().sorted(reverseComparator).collect(Collectors.toList());
System.out.println("*** Unsorted ***");
filesList.forEach(SortTest::processFile);
System.out.println("*** Sort ***");
forwardOrder.forEach(SortTest::processFile);
System.out.println("*** Reverse Sort ***");
reverseOrder.forEach(SortTest::processFile);
}
private static void processFile(File file) {
try {
if (file.isFile()) {
System.out.println(file.getCanonicalPath() + " - " + new Date(file.lastModified()));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Sort file list with java 8 Collections使用 java 8 Collections 对文件列表进行排序
Example how to use Collections and Comparator Java 8 to sort a File list.示例如何使用集合和比较器 Java 8 对文件列表进行排序。
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<File> 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()));
}
}
For reverse sorting just change the order of x1, x2 for calling the x1.compareTo(x2) method the result will be reverse to one another对于反向排序,只需更改 x1、x2 的顺序即可调用 x1.compareTo(x2) 方法,结果将彼此相反
Default order默认订单
List<String> sortedByName = citiesName.stream().sorted((s1,s2)->s1.compareTo(s2)).collect(Collectors.toList());
System.out.println("Sorted by Name : "+ sortedByName);
Reverse Order相反的顺序
List<String> reverseSortedByName = citiesName.stream().sorted((s1,s2)->s2.compareTo(s1)).collect(Collectors.toList());
System.out.println("Reverse Sorted by Name : "+ reverseSortedByName );
Instead of all these complications, this simple step should do the trick for reverse sorting using Lambda .sorted(Comparator.reverseOrder())而不是所有这些复杂的事情,这个简单的步骤应该使用 Lambda .sorted(Comparator.reverseOrder())进行反向排序
Arrays.asList(files).stream()
.filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
.sorted(Comparator.reverseOrder()).skip(numOfNewestToLeave)
.forEach(item -> item.delete());
You can define your Comparator with your own logic like this;你可以像这样用你自己的逻辑定义你的比较器;
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());
};
And use it inside foreach as:并在 foreach 中使用它作为:
list.stream()
.sorted(sortCredentialsByLastLogin.reversed())
.collect(Collectors.toList());
//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);
If you want to sort by Object's date type property then如果要按对象的日期类型属性排序,则
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.