3 回答

TA貢獻1797條經驗 獲得超4個贊
首先,對所有動物進行計數,然后選擇出現多次的動物:
import static java.util.stream.Collectors.*;
.....
Map<Class<? extends Animal>, Long> animalCounts = animals.stream()
.flatMap(
lst -> lst.stream()
.map(a -> a.getClass())
.distinct() // in case several of the same animal are in the same place
)
.collect(groupingBy(x -> x, counting()));
List<Class<? extends Animal>> animalTypes = animalCounts.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(toList());

TA貢獻1785條經驗 獲得超4個贊
首先,也許您應該嘗試使用flatMap而不是map。
animals.stream()。map(place-> place.stream()。map(animal-> animal.getClass())。collect(Collectors.toSet()));
其次,實際上我們可以使用外部ConcurrentHashMap做到這一點,這將使我們能夠parallel在需要時使用。
ConcurrentHashMap<Class, AtomicLong> theCounterMap = new ConcurrentHashMap<>();
animals.stream().flatMap(list -> list.stream().map(animal -> animal.getClass()).distinct())
.forEach(clazz -> theCounterMap.computeIfAbsent(clazz, k -> new AtomicLong()).getAndIncrement());
List<Class> classList = theCounterMap.entrySet().stream()
.filter(entry -> entry.getValue().get() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
但是,如果您需要跟蹤源列表(作為兩個不同的位置),則需要進一步修改上面的解決方案。
更新
根據@shmosel的建議,您可以直接使用一種更簡單的方法來實現相同的目標,如下所示:
Map<Class, Long> theCounterMap = animals.stream().flatMap(list -> list.stream().map(animal -> animal.getClass()).distinct())
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
List<Class> classList = theCounterMap.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
添加回答
舉報