2

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!

SCoder20
  • 55
  • 1
  • 6

1 Answers1

4

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]
Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40
  • Thanks. One more question, how could I print the value and the first element in the array corresponding to the value? For example: "Something 150". – SCoder20 Dec 21 '21 at 23:44
  • 1
    If you just want to print something, you can use this: `map.forEach((key, value) -> System.out.println(key + " " + value[0]));` – Ervin Szilagyi Dec 21 '21 at 23:51