Hakan Kiyar Hakan Kiyar - 1 year ago 98
Java Question

Java StreamAPI: not sorting Map by its Instant-Keys

im trying to group a list of Instant-Timestamps and sort them due to their natural ordering.

public void testName() throws Exception {

List<Instant> asList = Arrays.asList(createInstants());

Map<Instant, List<Instant>> collect = asList.stream().sorted().collect(Collectors.groupingBy((Instant instant) -> instant));



public Instant[] createInstants() {
Instant instant1 = Instant.from(ZonedDateTime.of(2016, 12, 25, 12, 25, 30, 0, ZoneId.systemDefault()));
Instant instant2 = Instant.from(ZonedDateTime.of(2013, 8, 11, 13, 33, 45, 0, ZoneId.systemDefault()));
Instant instant3 = Instant.from(ZonedDateTime.of(2010, 3, 15, 13, 33, 45, 0, ZoneId.systemDefault()));

return new Instant[] { instant1, instant2, instant3 };

But it doesnt seem to work. Instead of :

{2016-12-25T11:25:30Z=[2016-12-25T11:25:30Z], 2013-08-11T11:33:45Z=[2013-08-11T11:33:45Z],2010-03-15T12:33:45Z=[2010-03-15T12:33:45Z]}

im getting this:

{2016-12-25T11:25:30Z=[2016-12-25T11:25:30Z], 2010-03-15T12:33:45Z=[2010-03-15T12:33:45Z], 2013-08-11T11:33:45Z=[2013-08-11T11:33:45Z]}

In other words: the result is not sorted. Why?

Answer Source

The Collectors.groupingBy() overload you're using doesn't return an ordered map. If you want your result to be ordered, you can specify LinkedHashMap with another overload:

Collectors.groupingBy((Instant instant) -> instant), LinkedHashMap::new, Collectors.toList())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download