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?
Method 2: Using the map() method A map is a collection of elements where each element is stored as a key, value pair. The objects of map type can hold both objects and primitive values as either key or value. On traversing through the map object, it returns the key, value pair in the same order as inserted.
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With