I'm trying to use Java 8 stream to check if all the distinct characters in a string are present in a map and to return their keys as a List. I am able to do it using Stream like below:
...
map.put("Apple",'a');
map.put("Ball",'b');
map.put("Cat",'c');
map.put("Doll",'d');
String format = "aabbbc";
List<String> list = format.chars().mapToObj(i -> (char) i).distinct()
.map(c -> map.entrySet().stream()
.filter(entry -> entry.getValue() == c).findFirst().get().getKey())
.collect(Collectors.toList());
So this returns me ["Apple","Ball","Cat"]
. However, I would have an input where the character might not be in the map. For example: format = "aabbbczzzzz"
In this case, I want to throw an exception saying that the Character is not found in the map. So I did this
List<String> list = format.chars()
.mapToObj(i -> (char) i)
.distinct()
.map(c -> map.entrySet().stream()
.filter(entry -> entry.getValue() == c)
.findFirst()
.orElseThrow(() -> new Exception("Character not found in Map")))
.collect(Collectors.toList());
But Java doesn't let me compile. Please help me with how to handle my requirement.