7

Currently the code use plain old foreach loop

String preEvalObj = new String("123");
for(Map.Entry<String, Float> entry : someHashMap.entrySet()){
  String key = entry.getKey();
  Float value = entry.getValue();
  if(preEvalObj.equals(key)){
    lambda1Onvalue...
  }else{
    lambda2lambda1Onvalue..
  }
}

And I'm trying to achieve something like

someHashMap.entrySet().stream().apply((key,value) -> if preEvalObj.equals(key) lambda1 else lambda2)

Can I use streams to achieve my goal?

Naman
  • 27,789
  • 26
  • 218
  • 353
DsCpp
  • 2,259
  • 3
  • 18
  • 46
  • Do lambdas return something? What do you want to do with the mapped values? Put them in a list, map, just consume the values different, as per each key? – fps Sep 03 '18 at 17:45

2 Answers2

3

One possible way(not using streams though) could be to iterate over the key, value pair (BiConsumer implementation) as:

someHashMap.forEach((key, value) -> {
    if (preEvalObj.equals(key)) {
        someOpsOnValue(); // lambda1Onvalue
    } else {
        someOtherOpsOnValue(); // lambda2lambda1Onvalue
    }
});

or the same expressed as a little more readable at least IMHO

BiConsumer<String, Float> biConsumer = (key, value) -> {
    if (key.equals("123")) { // preEvalObj
       someOpsOnValue(); // lambda1Onvalue
    } else {
       someOtherOpsOnValue(); // lambda2lambda1Onvalue..
    }
};

someHashMap.forEach(biConsumer);

Side note, the constructor is redundant for String initialisation -

String preEvalObj = "123";
Naman
  • 27,789
  • 26
  • 218
  • 353
  • 1
    Exactly, Thanks a lot:) – DsCpp Sep 03 '18 at 17:31
  • 2
    But mind the existence of dedicated lookup methods, like `Map.get(…)`, which work way more efficient than iterating over all mappings and calling `equals` on each key. – Holger Sep 04 '18 at 13:54
1

Using @nullpointer's answer, if the goal is to alter the values, you can do it like this

myHashMap.entrySet().stream().forEach(e -> {
      if (!e.getKey().equals(trigger))
          e.setValue(setNewValue);
      else
          e.setValue(setOtherNewValue);
  });
}
DsCpp
  • 2,259
  • 3
  • 18
  • 46