在单个循环中以声明方式分别按多个字段对Java流进行分组 [英] Java Stream Grouping by multiple fields individually in declarative way in single loop

查看:73
本文介绍了在单个循环中以声明方式分别按多个字段对Java流进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用它搜索了一下,但是我发现大多数情况是按汇总字段分组或更改流响应的情况,但以下情况并非如此:

I googled for it but I mostly found cases for grouping by aggregated fields or on to alter response of stream but not the scenario below:

我有一个 User 类,其中的字段为 category marketingChannel .

I have a class User with fields category and marketingChannel.

我必须编写一种声明式的方法,该方法接受用户列表并根据以下信息对用户进行计数 category ,并且还分别基于 marketingChannel (即不是 groupingBy(...,groupingBy(..))).

I have to write a method in the declarative style that accepts a list of users and counts users based on category and also based on marketingChannel individually (i.e not groupingBy(... ,groupingBy(..)) ).

我无法在单个循环中执行此操作.这是我必须实现的.

I am unable to do it in a single loop. This is what I have to achieve.

我编码了以下几种方法:

I coded few methods as follows:

import java.util.*;
import java.util.stream.*;
public class Main
{
    public static void main(String[] args) {
        List<User> users = User.createDemoList();
        imperative(users);
        declerativeMultipleLoop(users);
        declerativeMultipleColumn(users);
    }
    
    public static void imperative(List<User> users){
        Map<String, Integer> categoryMap = new HashMap<>();
        Map<String, Integer> channelMap = new HashMap<>();
        for(User user : users){
           Integer  value = categoryMap.getOrDefault(user.getCategory(), 0);
           categoryMap.put(user.getCategory(), value+1);
           value = channelMap.getOrDefault(user.getMarketingChannel(), 0);
           channelMap.put(user.getMarketingChannel(), value+1);
        }
        System.out.println("imperative");
        System.out.println(categoryMap);
        System.out.println(channelMap);
    }
    
    public static void declerativeMultipleLoop(List<User> users){
        Map<String, Long> categoryMap = users.stream()
        .collect(Collectors.groupingBy(
            User::getCategory, Collectors.counting()));
        Map<String, Long> channelMap = users.stream()
        .collect(Collectors.groupingBy(
            User::getMarketingChannel, Collectors.counting()));
        System.out.println("declerativeMultipleLoop");
        System.out.println(categoryMap);
        System.out.println(channelMap);
    }
    
    public static void declerativeMultipleColumn(List<User> users){
        Map<String, Map<String, Long>> map = users.stream()
        .collect(Collectors.groupingBy(
            User::getCategory,
            Collectors.groupingBy(User::getMarketingChannel, 
            Collectors.counting())));
       
        System.out.println("declerativeMultipleColumn");
        System.out.println("groupingBy category and marketChannel");
        System.out.println(map);
        
        Map<String, Long> categoryMap = new HashMap<>();
        Map<String, Long> channelMap = new HashMap<>();
        
        for (Map.Entry<String, Map<String, Long>> entry: map.entrySet()) {
            String category = entry.getKey();
            Integer count = entry.getValue().size();
            Long value = categoryMap.getOrDefault(category,0L);
            categoryMap.put(category, value+count);
            for (Map.Entry<String, Long> channelEntry : entry.getValue().entrySet()){
                String channel = channelEntry.getKey();
                Long channelCount = channelEntry.getValue();
                Long channelValue = channelMap.getOrDefault(channel,0L);
                channelMap.put(channel, channelValue+channelCount);
            }
        }
        System.out.println("After Implerative Loop on above.");
        System.out.println(categoryMap);
        System.out.println(channelMap);
    }
}
class User{
    private String name;
    private String category;
    private String marketChannel;
    
    public User(String name, String category, String marketChannel){
        this.name = name;
        this.category = category;
        this.marketChannel = marketChannel;
    }
    public String getName(){
        return this.name;
    }
    public String getCategory(){
        return this.category;
    }
    public String getMarketingChannel(){
        return this.marketChannel;
    }
    
     @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(name, user.name) &&
                Objects.equals(category, user.category) &&
                Objects.equals(marketChannel, user.marketChannel);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, category, marketChannel);
    }
    public static List<User> createDemoList(){
        return Arrays.asList(
            new User("a", "student","google"),
            new User("b", "student","bing"),
            new User("c", "business","google"),
            new User("d", "business", "direct")
            );
    }

方法 declerativeMultipleLoop 是声明性的,但每个字段都有一个单独的循环.复杂度:O(noOfFields *用户数)

The method declerativeMultipleLoop is declarative but it has a separate loop for each field. Complexity : O(noOfFields * No of users)

问题出在 declerativeMultipleColumn 方法中,因为我最终编写了命令式代码和多个循环.

The problem is in declerativeMultipleColumn Method as I end up writing imperative code and multiple loops.

我想以完全声明性和尽可能高效的方式编写上述方法.即复杂度:O(用户数)

I want to write the above method in completely declarative and as efficient as possible. i.e Complexity : O(No of users)

示例输出:

当务之急
{business = 2,student = 2}
{direct = 1,google = 2,bing = 1}
declerativeMultipleLoop
{business = 2,student = 2}
{direct = 1,google = 2,bing = 1}
declerativeMultipleColumn
按类别和marketChannel分组
{business = {direct = 1,google = 1},学生= {google = 1,bing = 1}}
在上面的强制循环之后.
{business = 2,student = 2}
{direct = 1,google = 2,bing = 1}

imperative
{business=2, student=2}
{direct=1, google=2, bing=1}
declerativeMultipleLoop
{business=2, student=2}
{direct=1, google=2, bing=1}
declerativeMultipleColumn
groupingBy category and marketChannel
{business={direct=1, google=1}, student={google=1, bing=1}}
After Implerative Loop on above.
{business=2, student=2}
{direct=1, google=2, bing=1}

推荐答案

如果我理解您的要求,那就是使用单个流操作来生成2张单独的地图.这将需要一个结构来保存地图,并需要一个收集器来构建该结构.类似于以下内容:

If I understand your requirement it is to use a single stream operation that results in 2 separate maps. That is going to require a structure to hold the maps and a collector to build the structure. Something like the following:

class Counts {
    public final Map<String, Integer> categoryCounts = new HashMap<>();
    public final Map<String, Integer> channelCounts = new HashMap<>();

    public static Collector<User,Counts,Counts> countsCollector() {
        return Collector.of(Counts::new, Counts::accept, Counts::combine, CONCURRENT, UNORDERED);
    }

    private Counts() { }

    private void accept(User user) {
        categoryCounts.merge(user.getCategory(), 1, Integer::sum);
        channelCounts.merge(user.getChannel(), 1, Integer::sum);
    }

    private Counts combine(Counts other) {
        other.categoryCounts.forEach((c, v) -> categoryCounts.merge(c, v, Integer::sum));
        other.channelCounts.forEach((c, v) -> channelCounts.merge(c, v, Integer::sum));
        return this;
    }
}

然后可以将其用作收集器:

That can then be used as a collector:

Counts counts = users.stream().collect(Counts.countsCollector());
counts.categoryCounts.get("student")...

(仅观点:在这种情况下,命令性和声明性之间的区别是任意的.对我来说,定义流操作感觉是程序性的(与Haskell中的等效性相反).

(Opinion only: the distinction between imperative and declarative is pretty arbitrary in this case. Defining stream operations feels pretty procedural to me (as opposed to the equivalent in, say, Haskell)).

这篇关于在单个循环中以声明方式分别按多个字段对Java流进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆