list中某列一样的数据放入map

本文介绍了一个使用Java Stream API对SupplierProductImage对象列表按ID进行分组的示例。通过创建SupplierProductImage实例并使用stream().collect(Collectors.groupingBy())方法,将列表中的元素按照指定属性进行分组,最后将结果转换为JSON字符串输出。

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.cj.supplier.model.SupplierProductImage;

public class test {

    public static void main(String[] args){
        List<SupplierProductImage> list = new ArrayList<> ();
        SupplierProductImage sp = new SupplierProductImage ();
        sp.setId (123L);
        sp.setImageUrl ("123");
        list.add (sp);
        SupplierProductImage sp1 = new SupplierProductImage ();
        sp1.setId (1234L);
        sp1.setImageUrl ("1234");
        list.add (sp1);
        SupplierProductImage sp2 = new SupplierProductImage ();
        sp2.setId (123L);
        sp2.setImageUrl ("123dd");
        list.add (sp2);
        
        Map<Long, List<SupplierProductImage>> collect = list.stream().collect(Collectors.groupingBy(SupplierProductImage::getId));
        System.out.println (JSON.toJSONString (collect));

    }
}

### Java 中将 `List` 转换为 `Map` 并去重 在Java中处理复杂的数据结构如 `List<Map<String, Object>>` 的时候,可以利用Stream API来简化操作流程。对于给定的任务——即把 JSON 格式的表转换成 Map 同时去除重复项——可以通过以下方式实现: #### 使用 Stream API 和 Collectors.toMap 方法 通过使用 `Collectors.toMap()` 可以方便地完成从 `List` 到 `Map` 的转换,并在此过程中指定键冲突解决策略从而达到去重的效果。 ```java import java.util.*; import java.util.stream.Collectors; public class TestLambdaMap { public static void main(String[] args) { // 假设有一个包含多个相同 key-value 对的 List<Map> List<Map<String, String>> listMaps = Arrays.asList( new HashMap<>() {{ put("id", "1"); put("name", "张三"); }}, new HashMap<>() {{ put("id", "2"); put("name", "李四"); }}, new HashMap<>() {{ put("id", "1"); // duplicate entry with different name but same id put("name", "王五"); }} ); // 将 List<Map> 转换为 Map<String, Map<String, String>>, 使用 id 作为唯一键 Map<String, Map<String, String>> uniqueMapById = listMaps.stream() .collect(Collectors.toMap( m -> m.get("id"), // 键映射函数 Function.identity(), // 值映射函数 (existing, replacement) -> existing // 解决键冲突的方式:保留第一个遇到的对象 )); System.out.println(uniqueMapById); // 如果想要获取的是一个 List<Map>, 那么可以在最后一步再转回去 List<Map<String, String>> resultListWithoutDuplicates = new ArrayList<>(uniqueMapById.values()); System.out.println(resultListWithoutDuplicates); } } ``` 上述代码展示了如何基于特定字段(这里是 `"id"` 字段)对 `List<Map>` 进行去重[^1]。当存在具有相同键的不同条目时,这里选择了保持第一次出现的那个记录不变而忽略后续相同的键值组合[^3]。 另外,在实际应用中可能还需要考虑其他因素,比如是否允许覆盖旧值等问题。这取决于具体业务逻辑的需求以及数据的一致性和准确性要求。 #### 处理更复杂的场景 如果需要根据更多的条件来进行比较或合并,则可以根据实际情况调整收集器的行为。例如,可以自定义二元运算符来自定义处理两个冲突对象之间的关系;也可以先按某些标准排序后再做进一步的操作等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值