【发布时间】:2019-05-10 11:46:59
【问题描述】:
我有一个List<Person> 对象。从中我想获得所有 id 的列表,并且我总是希望 id “abc”和“bob”作为列表的第 0 和第 1 个索引(如果可用)。有没有办法用java流做到这一点?
class Person {
private String id;
}
List<Person> allPeople = ...
List<String> allIds = allPeople.stream().map(Person::id).collect(Collectors.toList());
我的做法是:
Set<String> allIds = allPeople.stream().map(Person::id).collect(Collectors.Set());
List<String> orderedIds = new ArrayList<>();
if(allIds.contains("abc")) {
orderedIds.add("abc");
}
if(allIds.contains("bob")) {
orderedIds.add("bob");
}
//Iterate through the set and all add all entries which are not bob and abc in the list.
【问题讨论】:
标签: java java-8 java-stream comparator