First, I wanna show my code:
public static void main(String[] args)
{
Map<String,Integer> map = new LinkedHashMap<String,Integer>();
map.put("bye",0);
map.put("Hello",1);
System.out.println(Arrays.toString(map(map, new BiConsumer<String,Integer>(){
@Override
public void accept(String s, Integer i){
s=s+"s";
}
})));
}
public static String[] map(Map<String,Integer> m, BiConsumer<String,Integer> bif){
String[] key = m.keySet().toArray(new String[0]);
String[] entries = new String[m.size()];
for (int i = 0; i < m.size(); i++) {
bif.accept(key[i],m.get(key[i]));
entries[i] = key[i] + ", " + m.get(key[i]);
}
return entries;
}
As you can see, I would like to develop a method that accepts a Map<String, Integer> and BiConsumer<String, Integer>, that does what the passed function wants to do with every key and value from the map and that finally returns a String array.
One could say: a method that does roughly that what forEach does: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#forEach-java.util.function.BiConsumer-
I was able to add the BiConsumer interface because it doesn't depend on other Java 8 classes.
I need to develop this method without changing anything in the following code as possible and only with Java 7:
System.out.println(Arrays.toString(map(map, new BiConsumer<String,Integer>(){
@Override
public void accept(String s, Integer i){
s=s+"s";
}
})));
Expected result:
[byes, 0, Hellos, 1]
But I am getting:
[bye, 0, Hello, 1]
So I don't know, whether I should change the string within a method that is just outside the method.
Do you have any ideas?