我有一个 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.
最佳答案
看起来你需要更多的 PriorityQueue
而不是 List
这里,所以可能是这样的:
PriorityQueue<String> pq = list.stream()
.map(Person::getId)
.distinct()
.collect(Collectors.toCollection(() -> new PriorityQueue<>(
Comparator.comparing(x -> !"abc".equals(x))
.thenComparing(x -> !"bob".equals(x)))));
如果你仍然需要一个 List
,只需将 pq
变成一个:
List<String> result = new ArrayList<>();
while (!pq.isEmpty()) {
result.add(pq.poll());
}
关于Java收集列表但指定预定义的前两个元素顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53691061/