List合并相关

合并两个不同对象的List

这段代码的主要功能是将List<Pool1>List<Pool2>合并为一个新的List<Pool>,并且确保新的List中包含了所有属性。

  • ListUtils.union方法合并了这两个集合
  • JSON.toJSONString方法将合并后的List<Object>转换为JSON字符串
  • JSONArray.parseArray方法将JSON字符串转换为List<Pool>

import com.alibaba.fastjson.JSON; // 引入Apache Commons Collections库中的ListUtils类
import org.apache.commons.collections4.ListUtils; // 引入FastJSON库中的JSON类


		List<Pool1> list1 = new ArrayList<Pool1>() {
			{
				add(new Pool1("A", 1));
				add(new Pool1("B", 2));
			}
		};

		List<Pool2> list2 = new ArrayList<Pool2>() {
			{
				add(new Pool2("A", 1));
				add(new Pool2("B", 5));
			}
		};


		String str = JSONArray.toJSONString(ListUtils.union(list1, list2));
		List<Pool> list = JSONArray.parseArray(str, Pool.class);
		
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	public static class Pool1 {
		private String name;
		private Integer value;
	}

	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	public static class Pool2 {
		private String org;
		private Integer age;
	}


	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	public static class Pool {
		private String name;
		private Integer value;
		private String org;
		private Integer age;
	}

List中对象属性的合并(去重并求和)

代码使用了 Collectors.toMap() 方法来将 name 属性作为键,将 Pool 对象本身作为值构建成 Map。在这个过程中,如果存在重复的键(即相同的 name),则会调用第三个参数指定的合并函数来处理冲突。

在合并函数中,对重复的 Pool 对象进行求和操作,然后返回新的值。最后,通过调用 values() 方法获取合并后的结果集合,并将其转换为 List 类型。


		List<Pool> list = new ArrayList<Pool>() {
			{
				add(new Pool("A", 1));
				add(new Pool("A", 2));
				add(new Pool("A", 3));
				add(new Pool("B", 4));
				add(new Pool("B", 5));
			}
		};
		
		List<Pool> result = new ArrayList<>(list.stream()
				.collect(Collectors.toMap(Pool::getName, Function.identity(), (o1, o2) -> {
					o1.setValue(o1.getValue() + o2.getValue());
					return o1;
				})).values());
				
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值