tembers
tembers

Reputation: 15

Map.merge doesnt add value to ArrayList

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

Answers (2)

Eran
Eran

Reputation: 393781

You are putting empty ArrayLists in the Map, and then you merge empty ArrayLists, which results in empty ArrayLists.

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

Michael
Michael

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

Related Questions