Home > Net >  Add items to an ArrayList inside a HashMap
Add items to an ArrayList inside a HashMap

Time:06-24

I'm trying to create a HashMap that goes through an ArrayList of characters and returns the characters as keys and the values as an ArrayList oof indexes where they showed up for example [X,X,Y,Z,X] would return a map like :

{
  X: [0,1,4];
  Y: [2];
  Z: [3];
}

I have this code but it`s not working because the add method returns a boolean and I need to return a new List:

/* turn the pattern into a List of characters
        turn the List into a HashMap with the keys as the characters and 
        the values as the indexes of the characters in the List
        */
        ArrayList<Character> listOfPatternChars = convertStringToCharList(userPattern);
        HashMap<Character,ArrayList<Integer>> mapOfPatternCharsIndex = new HashMap<Character,ArrayList<Integer>>();
        
        ArrayList<ArrayList<Integer>> arrayOfIndexes = new ArrayList<ArrayList<Integer>>();

        for (int i = 0; i < listOfPatternChars.size(); i  ) {
            mapOfPatternCharsIndex.putIfAbsent(listOfPatternChars.get(i), new ArrayList<Integer>());
            mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> v.add(i) );
        }

I guess in JavaScript I could use the spread operator and do something like (k, v) => [...v,i]

is there anything similar in Java?

CodePudding user response:

You can simply do something like:

mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> {v.add(i); return v;} );

CodePudding user response:

Is the following acceptable?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
        Map<Character, List<Integer>> map = new HashMap<>();
        String userPattern = "XXYZX";
        for (int i = 0; i < userPattern.length(); i  ) {
            Character key = userPattern.charAt(i);
            List<Integer> indexes = map.get(key);
            if (indexes == null) {
                indexes = new ArrayList<>();
            }
            indexes.add(i);
            map.put(key, indexes);
        }
        System.out.println(map);
    }
}

Running the above code produces the following output:

{X=[0, 1, 4], Y=[2], Z=[3]}

CodePudding user response:

You can use IntStream with Collectors.groupingBy to fetch all the characters and their corresponding indices from the list.

List<Character> charList = Arrays.asList('X', 'X', 'Y', 'Z', 'X');

Map<Character, List<Integer>> map = IntStream.range(0, charList.size())
        .boxed()
        .collect(Collectors.groupingBy(charList::get));

System.out.println(map);

Output:

{X=[0, 1, 4], Y=[2], Z=[3]}
  •  Tags:  
  • java
  • Related