Home > Back-end >  Java stream - if condition in collect(Collectors.toMap()) dees not work
Java stream - if condition in collect(Collectors.toMap()) dees not work

Time:06-06

Can someone tell why this is not working ? I want to set a rule that "if key equals 2 then set value 'changed'"

HashMap<Integer, String> mapOne = new HashMap<>();
    mapOne.put(7, "one");
    mapOne.put(5, "two");
    mapOne.put(10, "three");
    mapOne.put(2, "four");
    mapOne.put(9, "five");
    mapOne.put(6, "six");
    
    HashMap<Integer, String> mapTwo = new HashMap<>();
    
    mapTwo = mapOne
   .entrySet()
   .stream()
   .collect(Collectors.toMap(x -> x.getKey(),
           y -> {
               if(y.getKey().equals(2)) {
                   y.setValue("changed");
               }
           }
         ));

CodePudding user response:

The paramaters for Collectors.toMap have to return a value, if you do x -> x.something() or xClass::something return is done automatically but once you use x-> {} you have to do it manualy in your case i expect it would be

y -> {
  if(y.getKey().equals(2)) {
    return "changed";
  }
  return y.getValue();         
}

CodePudding user response:

Same as the answer from @Ralan, but avoiding the return statements:

y -> y.getKey().equals(2) ? "changed" : y.getValue()
  • Related