取map里的重复value

本文通过一个具体的Java代码示例,展示了如何使用Java Stream API来找出Map集合中重复出现的值,并将这些值收集到List和Set中。通过对Map的entrySet进行流操作,使用groupingBy和filter等方法,有效地处理了数据并识别出了重复项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Demo {
    public static void main(String[] args) {
        Map<String, String> tempMap = new HashMap<>();
        tempMap.put("aa", "1123");
        tempMap.put("bb", "hello");
        tempMap.put("cc", "hello");
        tempMap.put("dd", "456");
        tempMap.put("ee", "hello");
        tempMap.put("ff", "1234555");
        tempMap.put("gg", "456");
        tempMap.put("hh", "aaaa");
        tempMap.put("ii", "world");
        tempMap.put("jj", "aaa");
        List<String> valueList = tempMap.entrySet().stream().map(entry -> entry.getValue())
                .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
                .entrySet().stream().filter(entry -> entry.getValue() > 1)
                .map(entry -> entry.getKey()).collect(Collectors.toList());
        Set<String> valueSet = tempMap.entrySet().stream().map(entry -> entry.getValue())
                .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
                .entrySet().stream().filter(entry -> entry.getValue() > 1)
                .map(entry -> entry.getKey()).collect(Collectors.toSet());
        System.out.println(valueSet);
        System.out.println(valueList);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值