在多个字段上对 Stream 进行排序

Java 8示例使用比较器和方法按多个字段对对象 Stream 进行排序。此方法返回带有另一个比较器的字典顺序比较器。它具有与SQL group by子句相同的效果。Comparator.thenComparing()

1.为多个字段创建比较器

要对多个字段进行排序,我们必须首先为要对 Stream 进行排序的每个字段创建比较器。然后按所需顺序链接每个比较器,以对完成的排序进行逐个分组。

//first name comparator
Comparator<Employee> compareByFirstName = Comparator.comparing( Employee::getFirstName );

//last name comparator
Comparator<Employee> compareByLastName = Comparator.comparing( Employee::getLastName );

//Compare by first name and then last name (multiple fields)
Comparator<Employee> compareByFullName = compareByFirstName.thenComparing(compareByLastName);

//Using Comparator - pseudo code
list.stream().sorted( comparator ).collect();

2。 Java Stream 在多个字段上排序–示例

thenComparing()用于创建Comparator能够按多个字段排序的示例。

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();
		
		//Compare by first name and then last name
		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;
	}
}

程序输出。

[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]]

将您的问题留在注解部分,该部分与Java 8中对象 Stream 中多个字段的排序有关。

参考:

Comparator.thenComparing()Java文档

saigon has written 1445 articles

Leave a Reply