roger_that
roger_that

Reputation: 9791

Java: Assign sorted map keys via stream to an array

I am trying to assign map keys to an integer array after sorting the map.

This is what am trying:

java.util.stream.Stream<Map.Entry<Integer,Integer>> sorted = 
                            myMap.entrySet().stream().sorted(Map.Entry.comparingByValue());

and then this is how am assigning:

int [] hotels = new int[myMap.size()];
int i = 0;

Set<Integer> keys = myMap.keySet();
for(Integer k:keys){
       hotels[i++] = k;
}

But when I print the array, it does not print in sorted order but regular map order.

I know a method: forEach(System.out:: println) to print the values in the stream itself but not able to assign.

Whats the correct way?

Upvotes: 0

Views: 91

Answers (1)

ernest_k
ernest_k

Reputation: 45319

Your stream is not sorting the entry set of the map in place. Additionally, just calling sorted doesn't run any sorting code (there's no terminal operation executed).

You can use this to get an array sorted through your stream:

int[] hotels = myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .mapToInt(Map.Entry::getKey)
                .toArray();

Upvotes: 1

Related Questions