我正在使用java8中的stream API来处理我的集合。但是,我想知道使用此API按给定顺序对对象进行排序的一种优雅方法是什么。
SortedCollection = inputCollection.stream()
.map(e -> {
return new Element(e.id, e.color);
}).collect(Collectors.toList());
在这里,我想使用id属性对已映射的元素进行排序。
有什么想法吗?谢谢!
发布于 2018-02-02 23:31:18
只需使用如下所示的Stream#sorted
,并使用Element
ID的getter方法的名称。
inputCollection.stream()
.map(e -> new Element(e.id, e.color))
.sorted(Comparator.comparing(Element::getId))
.collect(Collectors.toList());
发布于 2018-10-19 06:44:40
完整的详细示例:可能对starter on Stream类有帮助。
public class Employee {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
int salary;
public Employee(String n, int s) {
this.name = n;
this.salary = s;
}
@Override
public String toString() {
return "[" + name + ", " + salary + "]";
}
public static void main(String[] args) {
List<Employee> list = new ArrayList<Employee>() {
{
add(new Employee("Joe", 50000));
add(new Employee("Jim", 75000));
add(new Employee("Tom", 80000));
add(new Employee("Jim", 70000));
add(new Employee("Steve", 55000));
add(new Employee("Jim", 100000));
add(new Employee("Joe", 59000));
add(new Employee("Rich", 88000));
}
};
List<Employee> listSorted = new ArrayList<Employee>();
Comparator<Employee> NameCommparator = Comparator.comparing(Employee::getName);
listSorted = list.stream().sorted(NameCommparator).collect(Collectors.toList());
System.out.println(listSorted);
//sorting on descending order
Comparator<Employee> SalaryCommparator = Comparator.comparing(Employee::getSalary);
listSorted = list.stream().sorted(SalaryCommparator.reversed()).collect(Collectors.toList());
System.out.println(listSorted);
}
}
发布于 2018-02-02 23:35:32
也许可以试试这个
SortedCollection = inputCollection.stream()
.map(e -> {
return new Element(e.id, e.color);
})
.collect(Collectors.collectingAndThen(Collectors.toList(), l -> l.sort(yourComparator)));
https://stackoverflow.com/questions/48585873
复制相似问题