Remove duplicate values from HashMap in Java

前端 未结 10 937
南旧
南旧 2020-12-09 21:02

I have a map with duplicate values:

(\"A\", \"1\");
(\"B\", \"2\");
(\"C\", \"2\");
(\"D\", \"3\");
(\"E\", \"3\");

I would like to the map

10条回答
  •  春和景丽
    2020-12-09 21:39

    Assuming that you use Java 8, it could be done using the Stream API with a Set that will store the existing values:

    Map map = new HashMap<>();
    map.put("A", "1");
    ...
    System.out.printf("Before: %s%n", map);
    
    // Set in which we keep the existing values
    Set existing = new HashSet<>();
    map = map.entrySet()
        .stream()
        .filter(entry -> existing.add(entry.getValue()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    System.out.printf("After: %s%n", map);     
    

    Output:

    Before: {A=1, B=2, C=2, D=3, E=3}
    After: {A=1, B=2, D=3}
    

    NB: Strictly speaking a predicate of a filter is not supposed to be stateful, it should be stateless as mentioned into the javadoc in order to ensure that the result remain deterministic and correct even if we use a parallel stream. However here, I assume that you don't intend to use a parallel stream such that this approach remains valid.

提交回复
热议问题