0

How to write code for the following logic in Java-8, here is my code

private static Integer getTheInteger() {
    Map<String, Integer> items = new HashMap<>();
    items.put("A", 10);
    items.put("B", 20);
    items.put("C", 30);
    items.put("D", 40);
    items.put("E", 50);
    items.put("F", 60);

    for (Map.Entry<String, Integer> entry : items.entrySet()) {
        if(entry.getKey().equals("E")) {
            return entry.getValue();
        }
    }
    return 0;
}
Naman
  • 27,789
  • 26
  • 218
  • 353
aruntheimperfect
  • 231
  • 1
  • 3
  • 11
  • For records, do take a look at [What should I do when someone answers my question?](https://stackoverflow.com/users/9110949/aruntheimperfect) – Naman Dec 24 '18 at 11:44

3 Answers3

4

You just need a get for it ideally. Additionally, to handle a default case(return 0 here) use Map.getOrDefault as in :

return items.getOrDefault("E", 0);
Naman
  • 27,789
  • 26
  • 218
  • 353
1

You don't need a loop for that, and you don't need any Java 8 functionality.

return items.get("E");

Or, to handle the 0 value when key is not in the Map:

return items.containsKey("E") ? items.get("E") : 0;
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    I guess I would find [`getOrDefault`](https://stackoverflow.com/a/53911413/1746118) better (opinion based), which though under the cover does the same check. – Naman Dec 24 '18 at 09:18
1

if you were to use a stream for this it would look like:

return items.entrySet()
            .stream()
            .filter(s -> "E".equals(s.getKey()))
            .findFirst().map(Map.Entry::getValue)
            .orElse(0);

but a better approach would be not to iterate over the map entries but instead use get() and depending on the result provide a default value.

return Optional.ofNullable(items.get("E")).orElse(0);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126