第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

從地圖內的列表中刪除重復的元素

從地圖內的列表中刪除重復的元素

慕村225694 2023-06-28 15:37:21
假設我有以下地圖:"A": [1, 2, 3, 4]"B": [5, 6, 1, 7]"C": [8, 1, 5, 9]如何從數組中刪除重復的元素,以便返回僅包含從未重復的元素的映射?"A": [2, 3, 4]"B": [6, 7]"C": [8, 9]
查看完整描述

2 回答

?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

您可能想這樣做:


// Initializing the map

Map<String, List<Integer>> map = new LinkedHashMap<String, List<Integer>>() {

    {

        put("A", new ArrayList<>(Arrays.asList(1, 2, 3, 4)));

        put("B", new ArrayList<>(Arrays.asList(5, 6, 1, 7)));

        put("C", new ArrayList<>(Arrays.asList(8, 1, 5, 9)));

    }

};


// finding the common elements

List<Integer> allElements = map.values().stream().flatMap(List::stream).collect(Collectors.toList());

Set<Integer> allDistinctElements = new HashSet<>();

Set<Integer> commonElements = new HashSet<>();

allElements.forEach(element -> {

    if(!allDistinctElements.add(element)) {

        commonElements.add(element);

    }

});


// removing the common elements

map.forEach((key, list) -> list.removeAll(commonElements));


// printing the map

map.forEach((key, list) -> System.out.println(key + " = " + list));

輸出:


A = [2, 3, 4]

B = [6, 7]

C = [8, 9]


查看完整回答
反對 回復 2023-06-28
?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

首先你必須計算每個列表中的數字

Map<Integer, Long> countMap = map.values().stream()
            .flatMap(List::stream)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

然后過濾其中 count == 1

Map<String, List<Integer>> result = map.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream()
                    .filter(i -> countMap.get(i) == 1).collect(Collectors.toList())));


查看完整回答
反對 回復 2023-06-28
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

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

公眾號

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