Java 8流,用于基于特定字段对对象列表进行排序 [英] java 8 stream for sorting a list of objects based on particular field
问题描述
我有一个根据时间戳对对象进行排序的方案.这些类如下:
I have a scenario to sort the objects based on timestamp. The classes are as follows:
class Employee
{
private String name;
private List<Address> addresses;
//...
//Getters and setters for all fields
}
public class Address
{
private String city;
private Timestamp startDate;
private Timestamp endDate;
private String typeOfResidence;
//...
//Getters and setters for all the fields
}
对于一名员工来说,有两种可能性 1.它将有一个地址列表. 2.地址列表可以为空
For an employee, there are 2 possibilities 1. it will have a list of address. 2. the list of address can be null
地址类具有字段typeOfResidence
,该字段可以具有诸如Residence,Office,ForeignHome之类的值.
The address class has a field typeOfResidence
which can have values such as Residence, Office, ForeignHome.
每个Employee
可以具有地址列表,一个地址将是住所",另一个地址是办公室",依此类推.可以有多个住宅地址,但只有一个办公室地址.
Each Employee
can have list of address, one address will be Residential, other Office and so on. There can be multiple Residential addresses but only one Office address.
我想根据typeDyResidence = Office的地址的startDate对员工列表进行排序.
I want to sort the list of employees based on startDate of Address whose typeOfResidence=Office.
我写了以下代码:
private void sortEmployeeListBasedOnStartDate(List<Employee> employeeList)
{
Comparator<Address> byTimeStamp = Comparator.comparing(
Address::getStarteDate,
(ts1, ts2) -> ts1.toGregorianCalendar().compareTo(ts2.toGregorianCalendar())
);
employeeList.stream()
.map(x -> getLatestAddressByType(x, "Office"))
.filter(y -> y!=null)
.sorted(byTimeStamp.reversed())
.collect(Collectors.toList());
}
public Address getLatestAddressByType(Employee employee, String type)
{
if(role != null && brokerageManagedProposalType != null)
{
return getUserAddress(employee).stream()
.filter(address-> address.getTypeOfResidence().equals(type))
.findFirst()
.orElse(null);
}
return null;
}
public List<Address> getUserAddress(Employee employee)
{
if (!NullChecker.isNull(employee) && !NullChecker.isNull(employee.getAddress()))
{
return employee.getAddress();
}
return Collections.emptyList();
}
这似乎不起作用.员工未排序.请帮助我使其正常工作.
Somehow this does not seem to be working. The employees are not sorted. Please help me to make it working.
推荐答案
如果要就地排序,可以使用Collections.sort
代替流.
If you want in-place sorting, you can use Collections.sort
instead of streams.
Collections.sort(employeeList,
(e1,e2) -> byTimeStamp.compare(
getLatestAddressByType(e2, "Office"),
getLatestAddressByType(e1, "Office") );
类似地,可以按如下方式就地解决null
过滤问题:
Similarly, the null
-filtering issue can be solved in-place as follows:
employeeList.removeIf(e -> getLatestAddressByType(e, "Office") == null);
(btw,getLatestAddressByType
应该是Employee
的实例方法)
(btw, getLatestAddressByType
should probably be an instance method of Employee
)
这篇关于Java 8流,用于基于特定字段对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!