I have a Map<String, Integer>, which has some keys and values. I want to associate all keys with the values as the key's length.
I have been able to solve this in pure java and java-8, but somehow I don't think that appending a terminal operation at the end like .collect(Collectors.toList()); which is not required for me in my code.
My code: ( Java ) works fine
Map<String, Integer> nameLength = new HashMap<>();
nameLength.put("John", null);
nameLength.put("Antony", 6);
nameLength.put("Yassir", 6);
nameLength.put("Karein", 6);
nameLength.put("Smith", null);
nameLength.put("JackeyLent",null);
for(Entry<String, Integer> length: nameLength.entrySet()){
if(length.getValue() == null){
nameLength.put(length.getKey(),length.getKey().length());
}
}
Java-8 also works fine but the terminal operation is useless, how I avoid it without using .foreach().
nameLength.entrySet().stream().map(s->{
if(s.getValue() == null){
nameLength.put(s.getKey(),s.getKey().length());
}
return nameLength;
}).collect(Collectors.toList());
System.out.println(nameLength);
Any other way in which I can do the above logic in Java-8 and above??
forEach?foreachloop with arcane constructs of streams and lambdas that barely do what original code did.map.. mutable operation, that doesn't return anything interesting