Java StreamAPI:不按其Instant-Keys排序Map

时间:2016-06-03 21:26:02

标签: java sorting java-stream

我试图将Instant-Timestamps列表分组,并根据它们的自然顺序对它们进行排序。

@Test
    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));

        System.out.println(collect);

    }

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 };
}

但它似乎没有用。而不是:

{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]}

我得到这个:

{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]}

换句话说:结果没有排序。为什么?

2 个答案:

答案 0 :(得分:1)

Collectors.groupingBy没有排序保证 - 实际上,它会返回HashMap

(而且,目前尚不清楚为什么你想要一张地图而不是一套?)

可能最简单的解决方案就是写

collect(toCollection(() -> new TreeSet<>()));

...收集到有序集合中。

答案 1 :(得分:1)

您使用的Collectors.groupingBy()重载不会返回有序地图。如果您希望对结果进行排序,可以使用another overload指定LinkedHashMap

Collectors.groupingBy((Instant instant) -> instant), LinkedHashMap::new, Collectors.toList())