Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using streams to apply different functions on key value pair depending on keys

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?

like image 666
DsCpp Avatar asked Sep 03 '18 17:09

DsCpp


People also ask

Which method uses key-value pair?

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.

How do you use key-value pairs in Java?

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.

Which method is used to add key and value pair in HashMap?

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.


1 Answers

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";
like image 105
Naman Avatar answered Nov 07 '22 10:11

Naman