Remove duplicate values from HashMap in Java

前端 未结 10 952
南旧
南旧 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

    This can be done using Java 8. The concept of stream is required. The pseudocode, is stream().filter().collect(). If the Initial Map : {A=1, B=2, C=2, D=3, E=3}. Then the required answer after removing the duplicates is {A=1, B=2, D=3} .

    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    public class RemoveDuplicates1 {
       public static void main(String[] args) {
    
            //Initial Map : {A=1, B=2, C=2, D=3, E=3}
            //After =>  {A=1, B=2, D=3} 
    
          Map map = new HashMap<>();
            map.put("A", "1");
            map.put("B", "2");
            map.put("C", "2");
            map.put("D", "3");
            map.put("E", "3");
    
            System.out.printf("before :   " +map );
            System.out.println("\n");
    
            Set set = new  HashSet<>();
    
            map = map.entrySet().stream()
                    .filter(entry -> set.add(entry.getValue()))
                    .collect(Collectors.toMap(Map.Entry :: getKey ,  Map.Entry :: getValue));
            System.out.printf("after => " + map);
    
       }
    }
    

提交回复
热议问题