如何在使用collect时避免多个流式传输

Ang*_*nes 5 readability jooq java-8 java-stream

我有一个使用jooq查询数据库并使用流后处理结果的组合.但是我觉得我的代码不是很易读,也不够简洁.如何以更好地表达我的意图的方式改进我的代码.

sql
    .select(field("USER_NAME", String.class))
    .from(table("CWD_USER"))
    .fetch()
    .stream()
    .map(f -> f.getValue(field("USER_NAME", String.class)))
    .collect(Collectors.groupingBy(s -> StringUtils.split(s, "-")[0], Collectors.counting()))
    .entrySet().stream()
    .sorted(new java.util.Comparator<Entry<String, Long>>() {
        @Override
        public int compare(Entry<String, Long> o1,
                Entry<String, Long> o2) {
            return o2.getValue().compareTo(o1.getValue());
        }
    })
    .forEach(e -> System.out.println(String.format("%13s: %3d", e.getKey(), e.getValue())));
Run Code Online (Sandbox Code Playgroud)

首先,我遇到了多个流媒体的问题.我首先从jooq流式传输结果然后我流式传输收集的地图.比较器似乎也很突出.当然我可以用它来制作课程,但也许有另一种解决方案.

Tag*_*eev 5

我不能说JOOQ部分,但Stream API部分看起来很好.您必须在分类之前中间收集以了解计数.请注意,这样的比较器已经在JDK中实现了:它是Map.Entry.comparingByValue().您可以使用它(添加Comparator.reverseOrder()参数以相反的顺序排序):

sql
    .select(field("USER_NAME", String.class))
    .from(table("CWD_USER"))
    .fetch()
    .stream()
    .map(f -> f.getValue(field("USER_NAME", String.class)))
    .collect(Collectors.groupingBy(s -> StringUtils.split(s, "-")[0], Collectors.counting()))
    .entrySet().stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    .forEach(e -> System.out.println(String.format("%13s: %3d", e.getKey(), e.getValue())));
Run Code Online (Sandbox Code Playgroud)