亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java:使用Stream API在嵌套列表中查找常見項目

Java:使用Stream API在嵌套列表中查找常見項目

素胚勾勒不出你 2021-05-06 21:20:59
假設我有一個List<List<Animal>> animals。此嵌套列表表示一個位置列表,其中每個位置都包含動物列表。我需要找出至少出現在兩個不同位置的動物類型列表。我知道我可以進行常規循環并執行該操作。有什么方法可以通過Stream API完成嗎?例子:List<List<Animal>> animals = new ArrayList<>();animals.add(Arrays.asList(new Dog(), new Cat()));animals.add(Arrays.asList(new Dog(), new Bird()));animals.add(Arrays.asList(new Bird()));預期(等同于):List<Class<? extends Animal>> animalTypes = Arrays.asList(Dog.class, Bird.class);至于嘗試,我只設法將內部列表轉換為一組類:animals.stream().map(place -> place.stream().map(animal -> animal.getClass()).collect(Collectors.toSet()));更新在沒有Stream API的情況下執行此操作的代碼:final List<List<Animal>> animals = new ArrayList<>();animals.add(Arrays.asList(new Dog(), new Cat()));animals.add(Arrays.asList(new Dog(), new Bird()));animals.add(Arrays.asList(new Bird()));final Map<Class<? extends Animal>, Integer> count = new HashMap<>();for (final List<Animal> place : animals) {    final Set<Class<? extends Animal>> uniqueTypes = new HashSet<>();    for (final Animal animal : place) {        uniqueTypes.add(animal.getClass());    }    for (final Class<? extends Animal> type : uniqueTypes) {        if (!count.containsKey(type))        {            count.put(type, 1);        }        else        {            count.put(type, count.get(type).intValue() + 1);        }    }}final List<Class<? extends Animal>> typesAppearingAtLeastAtTwoPlaces = new ArrayList<>();for (final Class<? extends Animal> type : count.keySet()) {    if (count.get(type).intValue() >= 2) {        typesAppearingAtLeastAtTwoPlaces.add(type);    }}System.out.println(typesAppearingAtLeastAtTwoPlaces);輸出:[class Test$Dog, class Test$Bird]
查看完整描述

3 回答

?
繁星coding

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());


查看完整回答
反對 回復 2021-05-12
?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

我認為您也可以嘗試StreamEx。它使您有機會編寫更簡潔,更易讀的代碼:

StreamEx.of(animals)
    .flatMap(e -> e.stream().map(Animal::getClass).distinct())
    .distinct(2).toList();


查看完整回答
反對 回復 2021-05-12
?
九州編程

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());


查看完整回答
反對 回復 2021-05-12
  • 3 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號