Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access values from map with ArrayList values in Java

I have Map with values as follows:
Map <Char, ArrayList> numbers;
A: {0,1,2,3}
B:{4,5,6,7}
Now, I can access ArrayLists using numbers.get('A')
but how do I access the elements of arraylist?
Also, I want to get store the elements at each index individually in ArrayList.
For example: ArrayList1: 0,4 and ArrayList2:1,5 and so on.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Arraylists are indexed, meaning that you can access elements by index with the get() method. nums.get(0) //returns first element in nums.

To group the elements at the same index together for numbers

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

public class Sol {
    public static void main(String[] args) {
       HashMap<String,ArrayList<Integer>> numbers = new HashMap<>();
       numbers.put("A",new ArrayList<>(List.of(0,1,2,3)));
        numbers.put("B",new ArrayList<>(List.of(4,5,6,7)));
        List<ArrayList<Integer>> values = numbers.values().stream().toList();
        HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
        for(int j = 0; j < values.get(0).size(); j++) {
            ArrayList<Integer> currCol = new  ArrayList<Integer>();
            for(int i = 0;i < values.size(); i++) {
                currCol.add(values.get(i).get(j));
            }
            map.put("ArrayList"+Integer.valueOf(j).toString(),currCol);
        }
        System.out.println("");
    }

}

I assumed that the number of items in each list is the same.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading