How to remove an element of a HashMap whilst streaming (lambda)

后端 未结 4 767
渐次进展
渐次进展 2020-12-13 23:44

I have the following situation where I need to remove an element from a stream.

map.entrySet().stream().filter(t -> t.getValue().equals(\"0\")).
                 


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 00:20

    1st time replying. Ran across this thread and thought to update if others are searching. Using streams you can return a filtered map<> or whatever you like really.

      @Test
      public void test() {
    
        Map map1 = new HashMap<>();
        map1.put("dan", "good");
        map1.put("Jess", "Good");
        map1.put("Jaxon", "Bad");
        map1.put("Maggie", "Great");
        map1.put("Allie", "Bad");
    
        System.out.println("\nFilter on key ...");
        Map map2 = map1.entrySet().stream().filter(x -> 
        x.getKey().startsWith("J"))
            .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
    
        map2.entrySet()
          .forEach(s -> System.out.println(s));
    
        System.out.println("\nFilter on value ...");
        map1.entrySet().stream()
          .filter(x -> !x.getValue().equalsIgnoreCase("bad"))
          .collect(Collectors.toMap(e -> e.getKey(),  e -> e.getValue()))
          .entrySet().stream()
          .forEach(s -> System.out.println(s));
      }
    
    ------- output -------
    
    Filter on key ...
    Jaxon=Bad
    Jess=Good
    
    Filter on value ...
    dan=good
    Jess=Good
    Maggie=Great
    
    

提交回复
热议问题