guava集合分组

本文通过一个具体的Java示例展示了如何使用Guava库中的Multimaps.index方法对商品对象列表按groupId属性进行分组,并将分组结果转换为Map结构以便于后续处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.google.common.base.Function;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
class Goods {
private Integer id;
private Integer groupId;
private String name;

public String toString() {
return "{id="+id + ", groupId=" + groupId + ", name=" + name + "}";
}
}
public class TxAspect {
public static void main(String[] args) {
List<Goods> list = new ArrayList<>();
{
Goods e = new Goods();
e.setId(1);
e.setGroupId(1);
e.setName("商品1");
list.add(e);
}

{
Goods e = new Goods();
e.setId(3);
e.setGroupId(3);
e.setName("商品3");
list.add(e);
}
{
Goods e = new Goods();
e.setId(4);
e.setGroupId(2);
e.setName("商品4");
list.add(e);
}
{
Goods e = new Goods();
e.setId(5);
e.setName("商品5");
list.add(e);
}
{
Goods e = new Goods();
e.setId(2);
e.setGroupId(2);
e.setName("商品2");
list.add(e);
}
//根据groupId分组, 如果groupId为null, 则放到默认为0的group下
Function<Goods, Integer> fun = new Function<Goods, Integer>() {
@Override
public Integer apply(Goods input) {
if (input.getGroupId() == null) {
return 0;
}
return input.getGroupId();
}
};
Multimap<Integer, Goods> index = Multimaps.index(list, fun);
Map<Integer, Collection<Goods>> map = index.asMap();
for (Map.Entry<Integer, Collection<Goods>> entry : map.entrySet()) {
System.out.println(entry.getKey() + " <---> " + entry.getValue());
}
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值