我正在使用Stream of Person数据,并且遇到了与数据相关的分区问题。
我有一个数据的Stream,我将在下面的表中表示:
ID Name Ticket IsEmployee
1 A Y Y
2 B
3 C Y
4 D我试图返回一个按以下顺序排序的List:
我研究了Collections.groupBy和Collections.partitioningBy,但是到目前为止还没有得到正确的结果。
我的期望是按以下顺序返回一个列表(按ID):
1 [name="A",Ticket="**[100,101]**", IsEmployee="**Y**"],
3 [name="C",Ticket="**[200,201]**", IsEmployee=""],
2 [name="**B**",Ticket="", IsEmployee=""],
4 [name="D",Ticket="", IsEmployee=""]对于如何在不完全分裂流的情况下完成这一任务,有什么想法吗?
下面是我的人的样子:
public class Person {
private long id;
private String name;
private List<Ticket> tickets;
private String employeeType; // This is just a 'Y'/'N' value. This property has morphed into something else but I'm stuck using it.
public long getId(){
return id;
}
public String getName(){
return name;
}
public List<Ticket> getTickets(){
return tickets;
}
public String getEmployeeType(){
return id;
}
// Setters are the exact same as getters, meaning I have no transient methods
}发布于 2016-11-02 10:30:33
因为你说的是“我正试图返回一个按…排序的列表”不清楚为什么开始寻找分组或分区,而不是针对问题描述的确切目标,获取一个List并根据您的标准对其进行排序:
// collect into a mutable List, if it isn’t a mutable List in the first place
List<Person> list=stream.collect(Collectors.toCollection(ArrayList::new));
// sort by your specified criterie (note: false < true)
list.sort(Comparator.comparing((Person p) -> !p.getEmployeeType().equals("y"))
.thenComparing(p -> p.getTickets().isEmpty())
.thenComparing(Person::getName) );您还可以将该操作指定为Stream操作的一部分,例如
List<Person> list=stream
.sorted(
Comparator.comparing((Person p) -> !p.getEmployeeType().equals("y"))
.thenComparing(p -> p.getTickets().isEmpty())
.thenComparing(Person::getName) )
.collect(Collectors.toList());但是没有技术上的好处。流实现必须在内部将整个内容收集到一个临时缓冲区中,在将其收集(即复制)到结果的List之前对其进行排序。ArrayList的就地排序可能会少一些,甚至没有数据复制(这对于四个元素来说并不重要,但一般情况下)。
https://stackoverflow.com/questions/40368701
复制相似问题