假设我有一个Map<Date, List<Integer>> ,其中整数列表只是彩票抽奖中抛出的数字列表。 它可能看起来像这样:
Wed Nov 15 13:31:45 EST 2017=[1, 2, 3, 4, 5, 6], Wed Nov 22 13:31:45 EST 2017=[7, 8, 9, 10, 11, 12], Wed Nov 29 13:31:45 EST 2017=[13, 14, 15, 16, 17, 18], Wed Dec 13 13:31:45 EST 2017=[1, 19, 20, 21, 22, 23], Wed Dec 20 13:31:45 EST 2017=[24, 25, 26, 27, 28, 29]我需要将该地图转换为地图,其中key是彩票号码,值是投掷号码的最后日期。 类似于:1 = Wed 12月13日13:31:45 EST 2017 2 = Wed Nov 15 13:31:45 EST等等到49。
所以,问题是:是否有可能使用Java 8流,如果是,那么如何。
提前致谢。
Let say I have a Map<Date, List<Integer>>, where list of integers is just a list of numbers thrown in lottery draw. It may look like this:
Wed Nov 15 13:31:45 EST 2017=[1, 2, 3, 4, 5, 6], Wed Nov 22 13:31:45 EST 2017=[7, 8, 9, 10, 11, 12], Wed Nov 29 13:31:45 EST 2017=[13, 14, 15, 16, 17, 18], Wed Dec 13 13:31:45 EST 2017=[1, 19, 20, 21, 22, 23], Wed Dec 20 13:31:45 EST 2017=[24, 25, 26, 27, 28, 29]I need to convert that map into the map, where key is the lottery number, and the value is the last date when the number was thrown. Something like: 1=Wed Dec 13 13:31:45 EST 2017 2=Wed Nov 15 13:31:45 EST 2017 etc till 49.
So, the question is: is it possible to make it with the Java 8 streams and if yes, then how.
Thanks in advance.
最满意答案
如果我没有弄错你正在寻找这样的东西(假设Date是Comparable ):
map.entrySet() .stream() .flatMap(x -> x.getValue().stream().map(y -> new AbstractMap.SimpleEntry<>(x.getKey(), y))) .collect(Collectors.groupingBy( Entry::getValue, Collectors.collectingAndThen( Collectors.maxBy(Comparator.comparing(Entry::getKey)), x -> x.get().getKey())));If I am not mistaken you are looking for something like this (assuming Date is Comparable):
map.entrySet() .stream() .flatMap(x -> x.getValue().stream().map(y -> new AbstractMap.SimpleEntry<>(x.getKey(), y))) .collect(Collectors.groupingBy( Entry::getValue, Collectors.collectingAndThen( Collectors.maxBy(Comparator.comparing(Entry::getKey)), x -> x.get().getKey())));更多推荐
发布评论