Java 8:按人员状态过滤地图<Long,Person>到List <Long>

Seb*_* S. 2 java lambda java-8

我正在尝试过滤a Map<Long, Person> people并仅返回状态为SUBSCRIBEDa 的这些人的ID List<Long>.以下是老式的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

Person类看起来如下:

class Person {
    private Long id;
    private PersonStatus status;

    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

我试过以下,但这只给了我一个List<Entry<Long, Person>>:

public List<Long> getSubscribedPeople() {
    return people.entrySet()
                 .stream()
                 .filter(e -> e.getValue().getStatus() == PersonStatus.SUBSCRIBED)
                 .collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

我不得不以map某种方式到流?

sla*_*dan 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
}
Run Code Online (Sandbox Code Playgroud)