Java 8:按人员状态过滤地图<long,person =“”>列出<long>

时间:2015-06-18 16:53:10

标签: java lambda java-8

我正在尝试过滤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流?

1 个答案:

答案 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
}