我正在尝试过滤Map<Long, Person> people
并仅返回SUBSCRIBED
中状态为List<Long>
的这些人的ID。以下是老式的代码:
public List<Long> getSubscribedPeople() {
final List<Long> subscribedPeople = new ArrayList<>();
for (final Map.Entry<Long, Person> entry : subscribedPeople.entrySet()) {
if (entry.getValue().getStatus() == PersonStatus.SUBSCRIBED) {
subscribedPeople.add(entry.getKey());
}
}
return subscribedPeople;
}
Person类如下所示:
class Person {
private Long id;
private PersonStatus status;
// getters and setters
}
我尝试了以下操作,但这只给了我一个List<Entry<Long, Person>>
:
public List<Long> getSubscribedPeople() {
return people.entrySet()
.stream()
.filter(e -> e.getValue().getStatus() == PersonStatus.SUBSCRIBED)
.collect(Collectors.toList());
}
我是否必须以某种方式map
流?
答案 0 :(得分:5)
在收集之前,将条目流映射到其键。否则你将有一个条目流。
public List<Long> getSubscribedPeople() {
return people.entrySet() // set of entries
.stream() // stream of entries
.filter(e -> e.getValue().getStatus() == PersonStatus.SUBSCRIBED) // stream of entries
.map(e -> e.getKey()) // stream of longs
.collect(Collectors.toList()); // list of longs
}