Reputation: 15
i have a map and try to add value to an arraylist.
Example: Key:1 Value:ArrayList(1), Key:2 Value:ArrayList(2), Key:3 Value:ArrayList(3,3)
String ss = "1233";
char[] a = ss.toCharArray();
Map<Character, ArrayList<Character>> mymap = new LinkedHashMap<>();
for (char c : a) {
mymap.merge(c,new ArrayList<>(c), (o,n)->{
o.addAll(n); return o;
});
}
but it doenst work, the value (ArrayList) is allways empty. What am I doing wrong? Debuger output:
mymap = {LinkedHashMap@418} size = 3
{Character@599} 1 -> {ArrayList@600} size = 0
key = {Character@599} 1
value = {ArrayList@600} size = 0
{Character@604} 2 -> {ArrayList@605} size = 0
key = {Character@604} 2
value = {ArrayList@605} size = 0
{Character@609} 3 -> {ArrayList@610} size = 0
key = {Character@609} 3
value = {ArrayList@610} size = 0
Upvotes: 1
Views: 71
Reputation: 393781
You are putting empty ArrayList
s in the Map
, and then you merge empty ArrayList
s, which results in empty ArrayList
s.
Try:
mymap.merge(c,new ArrayList<>(Arrays.asList(c)), (o,n)->{
o.addAll(n); return o;
});
or
mymap.merge(c,new ArrayList<>(List.of(c)), (o,n)->{
o.addAll(n); return o;
});
Now the Map
will contain:
{1=[1], 2=[2], 3=[3, 3]}
Upvotes: 2
Reputation: 44110
new ArrayList<>(c)
is not doing what you think it is. It is creating an empty list, with an initial capacity related to the integer value of the character.
It is not creating a list with a single element.
Upvotes: 2