I want to create a HashMap<String,Integer>
from an existing HashMap<String,Integer>
by applying some operations on the key of the Map.
Say suppose I have a String->
String sampleString= "SOSSQRSOP";`
then created a hashmap by taking only 3 characters from string like below(putting 0 as value):
Map<String, Integer> messages= new HashMap<>();
messages.put("SOS",0);
messages.put("SQR",0);
messages.put("SOP",0);
The Actual task is to find total no of different characters from given string "SOS" with each key in the map and assign the no to value of each key. Like below (End result):
Map<String, Integer> messages= new HashMap<>();
messages.put("SOS",0);
messages.put("SQR",2);
messages.put("SOP",1);
so I wrote code in java8 using stream given below:
Map<String,Integer> result= messages
.entrySet().stream()
.collect(Collectors.toMap(e-> e.getKey(),
e-> e.getKey().stream()
.forEach(x-> {
if(!"SOS".equals(x)){
char[] characters= {'S','O','S'};
char[] message= x.toCharArray();
for(int i=0; i< characters.length;i++){
int index=0;
if(characters[i] != message[i]){
messages.put(e.getKey(),++index);
}
}
}
});
));
I am getting compile error. Can anybody help me write the code using stream.
Edited: Also please describe other approaches to do this. BTW creating first hashmap from given string was required in my case.