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

How to access an array´s element from hashmap´s values? Java

I´m triying to access all the first elements from the arrays corresponding to the values in the hashmap thay I´ve created. I can access the first element from an array with one specific value but not all at once. Is there a way I can access all the first elements inside an array from the hashmap values? Or even loop through? And then print the value and the first element corresponding to the value? For example: Print "Something 150".

This is what I´ve tried:

public static void main(String[] args) {

    HashMap<String, int[]> map = new HashMap<String, int[]>();
    map.put("Something", new int[] {150, 2, 3});
    map.put("Something2", new int[] {1, 2, 3});
    //System.out.print(map.get("Something")[0]); //This works, and I get the first value from the array corresponding from the key "Something".

    System.out.println(map.values()[0]);//In this line I get this error: The type of the expression must be an array type but it resolved to Collection<int[]>Java(536871062)

}

Thanks in advance!

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

>Solution :

map.values() returns a Collections<int[]> on which we can stream and get the first element from each array:

int[] firstElements = map.values().stream().mapToInt(value -> value[0]).toArray();

System.out.println(Arrays.toString(firstElements)); //Prints: [1, 150]
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