我正在努力维护我想要的跨 Java 流操作的数据结构,这很可能是由于缺乏适当的理解和实践。
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 1, 1, 2, 3, 3, 3, 3);
//Group by
Map <Integer, Long> countGrouped = list.stream().collect(
Collectors.groupingBy(
x -> x, Collectors.counting()));
System.out.println("group by value, count " + countGrouped);
//Sort desc
Map <Integer, Long> descendingSorted = new LinkedHashMap<>();
countGrouped.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEachOrdered(x -> descendingSorted.put(x.getKey(), x.getValue()));
System.out.println("sorted " + descendingSorted);
//filter
Map <Integer, Long> filtered = new LinkedHashMap<>();
descendingSorted.entrySet().stream()
.filter(x -> x.getValue() >= 2)
.forEach(x -> filtered.put(x.getKey(), x.getValue()));;
System.out.println("filtered " + filtered);
//Split groups
Map<Object, List<Entry<Integer, Long>>> groups = filtered.entrySet().stream()
.collect(Collectors.groupingBy(x -> x.getValue()));
System.out.println("grouped " + groups);
}
}
导致
group by value, count {1=3, 2=1, 3=4}
sorted {3=4, 1=3, 2=1}
filtered {3=4, 1=3}
grouped {3=[1=3], 4=[3=4]}
这是正确的,但正如您所看到的,我正在逐渐进入更深奥的数据结构,没有特别的意义,如您所见,以(wtf?)结束Map<Object, List<Entry<Integer, Long>>>。虽然它可以只是一个Map<Int, Map<Int, Int>>.
所以具体问题是,如何转换和包含流操作产生的数据结构输出?
我已经看到 Collectors 提供了对 Map(...) 的转换操作,我想这是要走的路,但我无法(我认为是由于缺乏适当的知识)让它工作。
在这种情况下,在我看来,教学解释、链接到综合资源以更好地理解流和函数式编程或类似的东西,比针对特定情况的实际解决方案更有帮助(这对一个练习,但你明白了)
www说
神不在的星期二
相关分类