本例子主要使用stream进行多个字段的排序,使用了 comparators和Comparator.thenComparing()方法。比较器之间返回一个字典排序。他的排序效果有点像SQL中的group by条件。
1.创建一个多字段排序的比较器
想要使用Java 8的Stream进行多字段排序,首先我们需要对我们想要排序的字段及那些创建comparator。然后根据需求进行一个链式的排序顺序,以此来完成类似group by的排序效果。
如何创建比较器comparator:
//姓的比较器comparator
Comparator<Employee> compareByFirstName = Comparator.comparing( Employee::getFirstName );
//最后一个名字的比较器 comparator
Comparator<Employee> compareByLastName = Comparator.comparing( Employee::getLastName );
//比较第一个名字然后比较最后一个名字 (多字段)
Comparator<Employee> compareByFullName = compareByFirstName.thenComparing(compareByLastName);
//使用比较器Comparator - 伪代码
list.stream().sorted( comparator ).collect();
2. java 8 stream 多字段排序
排序例子:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main
{
public static void main(String[] args)
{
ArrayList<Employee> employees = getUnsortedEmployeeList();
//先比较姓然后比较名
Comparator<Employee> compareByName = Comparator
.comparing(Employee::getFirstName)
.thenComparing(Employee::getLastName);
List<Employee> sortedEmployees = employees.stream()
.sorted(compareByName)
.collect(Collectors.toList());
System.out.println(sortedEmployees);
}
private static ArrayList<Employee> getUnsortedEmployeeList()
{
ArrayList<Employee> list = new ArrayList<>();
list.add( new Employee(2l, "Lokesh", "Gupta") );
list.add( new Employee(1l, "Alex", "Gussin") );
list.add( new Employee(4l, "Brian", "Sux") );
list.add( new Employee(5l, "Neon", "Piper") );
list.add( new Employee(3l, "David", "Beckham") );
list.add( new Employee(7l, "Alex", "Beckham") );
list.add( new Employee(6l, "Brian", "Suxena") );
return list;
}
}
运行项目输出结果:
$title(Console)
[E[id=7, firstName=Alex, lastName=Beckham],
E [id=1, firstName=Alex, lastName=Gussin],
E [id=4, firstName=Brian, lastName=Sux],
E [id=6, firstName=Brian, lastName=Suxena],
E [id=3, firstName=David, lastName=Beckham],
E [id=2, firstName=Lokesh, lastName=Gupta],
E [id=5, firstName=Neon, lastName=Piper]]
上方输出结果表示已经实现多字段的字典排序,如果你有任何疑问欢迎在下面的评论区留言告诉我。
原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/243621.html