Java 8 多键分组 [英] Java 8 Grouping with Multiple Keys

查看:28
本文介绍了Java 8 多键分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻求一些帮助,以将具有多个键的列表中的对象列表分组.

I am looking for some help in grouping a list of objects from a list with multiple keys.

基本上,我有一个用户列表,其中包含他们的订单列表,我希望能够使用 UserName 和 Address 作为键将它们分组在一起.

Basically, I have a list of users which contains a list of their orders and I want to be able to group them together using UserName and Address as the keys.

示例数据:

<UserList>
        <User>
            <Username>user123</Username>
            <Address>London</Address>
            <TransactionList>
                <TransactionList>
                    <OrderNumber>1</OrderNumber>
                    <Cost>3683446.6600</Cost>
                </TransactionList>
            </TransactionList>
        </User>
              <User>
            <Username>user123</Username>
            <Address>London</Address>
            <TransactionList>
                <TransactionList>
                    <OrderNumber>3</OrderNumber>
                    <Cost>500</Cost>
                </TransactionList>
            </TransactionList>
        </User>
               <User>
            <Username>user12356</Username>
            <Address>Manchester</Address>
            <TransactionList>
                <TransactionList>
                    <OrderNumber>6</OrderNumber>
                    <Cost>90000</Cost>
                </TransactionList>
            </TransactionList>
        </User>
              <User>
            <Username>user12356</Username>
            <Address>Manchester</Address>
            <TransactionList>
                <TransactionList>
                    <OrderNumber>10</OrderNumber>
                    <Cost>100</Cost>
                </TransactionList>
            </TransactionList>
        </User>
    </UserList>

我想这样排序,这样每个用户只有一个实例,并且其相关事务根据用户名和地址分组在一个列表中:

I want to order it like this so that each user just has one instance and its related transactions are grouped in a list based off Username and Address:

<UserList>
        <User>
            <Username>user123</Username>
            <Address>London</Address>
            <TransactionList>
                <TransactionList>
                    <OrderNumber>1</OrderNumber>
                    <Cost>3683446.6600</Cost>
                </TransactionList>
                <TransactionList>
                    <OrderNumber>3</OrderNumber>
                    <Cost>500</Cost>
                </TransactionList>
            </TransactionList>
        </User>
         <User>
            <Username>user12356</Username>
            <Address>Manchester</Address>
            <TransactionList>
                <TransactionList>
                    <OrderNumber>6</OrderNumber>
                    <Cost>90000</Cost>
                </TransactionList>
                 <TransactionList>
                    <OrderNumber>10</OrderNumber>
                    <Cost>100</Cost>
                </TransactionList>
            </TransactionList>
        </User>
    </UserList> 
        

我尝试过使用地图:

Map<String, Map<String,List<User>>> map;

map = userLists.getUserList().stream()
                .collect(Collectors.groupingBy(User::getUserName, Collectors.groupingBy(User::getAddress)));

这只是我想做的事情,但我想知道是否有更好的方法使用 MultiKey Map 或类似的东西,然后遍历并在密钥匹配时放置交易列表.

This is slightly what I am looking to do but I was wondering if there was a better way using MultiKey Map or something like that and then iterate through and put a list of transactions if the key matched.

提前感谢您的帮助.

推荐答案

你的做法没有错,第一步是正确的:按userName对用户进行分组,然后address.就我个人而言,我会倒置它,因为更有可能有更多用户使用相同的地址,但就实现正确结果而言,顺序并不重要.

Your approach is not wrong, the first step is correct: to group the users by the userName and then address. Personally, I'd invert it since more likely there are more users with a same address, but the order is not important in terms of achieving a corect result.

我注意到预期的输出看起来像 List<User> 具有共同特征(userNameaddress)和串联 的用户减少>transactionList 列表.尽管带有复合键(例如 ${userName}_${address})的映射可能看起来很有帮助,但我宁愿选择 List,它顺便说一下,符合预期的输出.

I notice the expected output looks like List<User> with reduced users with common characteristic (userName and address) and concatenated transactionList lists. Although a map with a composite key (ex. ${userName}_${address}) might seem helpful, I'd rather choose the List<User>, which is in comppliant with, by the way, what the expected output is like.

所以,第二步是迭代所有这些条目并将Map中的List缩减为单个用户.每个 inner 条目将与单个用户相关联(因为 userNameaddress 两者).For-each 非常适合这项任务.给你:

So, the second step is to iterate all these entries and reduce List<User> within the Map into a single user. Each inner entry will be associated with a single user (because of both userName and address). For-each is more than suitable for this task. There you go:

Map<String, Map<String,List<User>>> map = userLists.stream()
     .collect(Collectors.groupingBy(
            User::getUserName, 
            Collectors.groupingBy(User::getAddress)));

List<User> list = new ArrayList<>();                 // stored output

map.forEach((userName, groupedByAddress) -> {        // for each 'userName'
    groupedByAddress.forEach((address, users) -> {   // ... and each 'address'
        User userToAdd = new User();                 // ...... create an 'User'
        userToAdd.setUserName(userName);             // ...... with the 'userName'  
        userToAdd.setAddress(address);               // ...... with the 'address'
        users.forEach(user -> {                      // ...... and of each the user's
            userToAdd.getTransactionList()           // .......... concatenate
                .addAll(user.getTransactionList());  // .......... all the transactions
        });
    });
});

Stream API 非常适合通过分组来获得中间结果,但是,如果要进一步减少,这将非常笨拙.

The Stream API is a good for grouping to get an intermediate result, however, for such futher reduction it would be very clumsy.

这篇关于Java 8 多键分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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