在Java Map中查找重复的值?

9
我想展示一个 HashMap 中的值。一个 HashMap 可能有重复的值(但没有重复的键),但我只想展示一个值。
所以我应该找到 Map 是否有重复的值。我知道我们可以遍历 Map 并使用 map.containsValue(value) 的布尔返回值。我想知道是否存在任何方法来查找 map 中的重复值,还是我应该自己编写代码?
9个回答

24

一个简单的解决方案是比较您的值列表和值集合的大小。

// pseudo-code
List<T> valuesList = map.values();
Set<T> valuesSet = new HashSet<T>(map.values);
// check size of both collections; if unequal, you have duplicates

这项技术很好,但如果我想要去除重复的意思,应该手动进行删除操作,对吗? - Silambarasan
是的,您将不得不进行手动操作。但是,如果您能向我解释确切的情况,例如您如何最终获得具有相同值的多个键以及为什么要删除它们,也许我可以提出更好的解决方案。 - Sanjay T. Sharma

6

例子:

Map<Object, Object> map = new HashMap<Object, Object>();
map.put(1,2);
map.put(3,4);
map.put(2,2);
map.put(5,3);

Set<Object> uniqueValues = new HashSet<Object>(map.values());

System.out.println(uniqueValues);

输出:

[2, 3, 4]

我该如何将这个添加到同一个地图中? - bot13
你可以将此作为一个新问题提出。请记得清楚地描述你想要实现什么,展示你已经尝试过的代码以及具体出了什么问题。 - Adriaan Koster

2

尝试使用这段代码

private boolean hasDuplicates(Map<Integer, List<String>> datamap){
boolean status = false;


    Set valueset=new HashSet(datamap.values());

    if(datamap.values().size()!=valueset.size()){
    status=true;
    }
    else{
    status = false;
    }


    return status;

}

它应该是最好的答案! - LgSus97

1

在jdk1.6中没有提供这样的方法。

你可以采用一种简单的方法:

  • 从map中获取所有值并放入列表中
  • 将该列表放入集合中,这将删除重复项

1
使用Apache Commons库类的方法。
org.apache.commons.collections.MapUtils.invertMap(map)

并比较实际地图和反转地图的大小。


1
public static void main(String[] args) {

        HashMap<String, Integer> map = new HashMap<>();
        map.put("abc", 2);
        map.put("def", 1);
        map.put("hij", 4);
        map.put("klm", 6);
        map.put("nop", 2);
        map.put("qrs", 2);
        map.put("tuv", 6);
        map.put("wxy", 8);
        map.put("zab", 1);
        map.put("cde", 5);
        map.put("fgh", 4);
        map.put("ijk", 3);

        HashMap<Integer, String> duplicatMap = new HashMap<>();

        Set<Entry<String, Integer>> entrySet = map.entrySet();
        Iterator<Entry<String, Integer>> iterator = entrySet.iterator();
        while(iterator.hasNext()) {
            Entry<String, Integer> entry = iterator.next();
            String key = entry.getKey();
            Integer value = entry.getValue();

            if(duplicatMap.containsKey(value)) {
                duplicatMap.put(value, duplicatMap.get(value)+", "+key);
            } else {
                duplicatMap.put(value, key);
            }
        }
        System.out.println(duplicatMap);

    } 

输出:- {1 = def,zab,2 = abc,qrs,nop,3 = ijk,4 = fgh,hij,5 = cde,6 = tuv,klm,8 = wxy} 如果您想修改,请再次使用EntrySet。


它只是打印所有内容。 - Krishnom

0
Map<Integer,Person> personMap01 = new HashMap<>();
personMap01.put(1,new Person(101,"Ram","Kumar"));
personMap01.put(2,new Person(103,"Raj","Kumar"));
personMap01.put(3,new Person(101,"Ravi","Ram"));
personMap01.put(4,new Person(105,"Gopi","Nath"));
personMap01.put(5,new Person(104,"Yogesh","Waran"));
personMap01.entrySet().stream().
filter(removeDuplicate(personMap01.values())).
forEach(System.out::println);

public static Predicate<Map.Entry<Integer,Person>> 
removeDuplicate(Collection<Person> personCollection){
    return e->Collections.frequency(personCollection,e.getValue())==1;
}

在Java8中从Map中删除自定义对象的重复值 - Yogesh

0
try this code but this is not optimize code :

public class HashMapDulicate {
    public static void main(String[] args) {        
        Map<String,Integer> map=new HashMap<>();
        map.put("A", 1);
        map.put("B", 1);
        map.put("C", 3);
        map.put("D", 4);


        Set set=new HashSet<>();
        List list=new ArrayList<>();

        for(Entry<String, Integer> mapVal:map.entrySet()) {

            if(!set.add(mapVal.getValue())) {
                list.add(mapVal.getValue());

            }else {
                set.add(mapVal.getValue());
            }

        }

for(Entry<String, Integer> mapVal:map.entrySet()) {

    if(list.contains(mapVal.getValue())){

        System.out.println(mapVal.getKey() +":" + mapVal.getValue());
    }
}
    }
}

0
在我的一次面试中,面试官要求我在不使用Set、Map和distinct的情况下打印重复项。
List<String> distinctElementList = new ArrayList<>();
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 4, 4, 5, 5, 6);

numberList.stream().forEach(number -> {
        if (distinctElementList.stream().anyMatch(numberStr -> numberStr.contains(String.valueOf(number)))) {
            String existStr = distinctElementList.stream().filter(numberStr -> numberStr.contains(String.valueOf(number))).findFirst().orElse("");
            Integer index = distinctElementList.indexOf(existStr);
            if (existStr.split("[|]").length == 2) {
                distinctElementList.set(index, number + "|" + (Integer.valueOf(existStr.split("[|]")[1]) + 1));
            }
        } else {
            distinctElementList.add(number + "|" + 1);
        }
});

distinctElementList.stream().filter(numberStr -> !numberStr.contains(String.valueOf(1))).forEach(
            numberStr -> {
                String keyValueArr[] = numberStr.split("[|]");
                System.out.println("Number : " + keyValueArr[0] + "--------------Count : "+keyValueArr[1]);
            }
);


System.out.println("Original List : " + numberList);
System.out.println("distinctElementList List : " + distinctElementList); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接