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

Time:12-22

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!

CodePudding user response:

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]

CodePudding user response:

Smells like homework, but a few suggestions -

  • there's no reason for your Hashmap to be of the form <String,Object> - make it <String, String[][]> , as that's what you're storing.

You're iterating twice. You either - iterate through the map, either the keys, values or entries. Each item is an iterator return value, e.g.

for (String[][] s:map.values()){
 ...
}
  • hashmap.values.toArray gives you all of the contents, which is the same thing your iterator is doing.

  • if you're only iterating through the contents, then you're not really using a map, as you're never making use of the fact that your values are available by key.

  •  Tags:  
  • java
  • Related