java 8 Stream List 转换成 Map

在Java 8中,Stream API 提供了多种将 List 转换成 Map 的方法,这些方法可以处理各种复杂的操作。以下是一些常用的转换操作,包括一些复杂的示例:

2024最全大厂面试题无需C币点我下载或者在网页打开全套面试题已打包

AI绘画关于SD,MJ,GPT,SDXL,Comfyui百科全书

基本转换操作

  1. 转换为键值映射
    如果列表中的元素已经是键值对,可以直接转换。

    List<Map.Entry<Key, Value>> list = ...
    Map<Key, Value> map = list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    
  2. 使用函数提取键和值
    如果列表中的元素不是键值对,可以提取对象的某个属性作为键或值。

    List<Item> list = ...
    Map<String, Item> map = list.stream()
                               .collect(Collectors.toMap(Item::getName, Function.identity()));
    
  3. 处理键值冲突
    当多个元素具有相同的键时,可以提供一个合并函数来解决冲突。

    Map<String, List<Item>> map = list.stream()
                                     .collect(Collectors.toMap(Item::getName,
                                                               Collectors.toList(),
                                                               (existing, replacement) -> existing));
    

复杂转换操作

  1. 转换为嵌套映射
    可以将列表中的每个元素转换成一个嵌套的映射结构。

    Map<String, Map<String, String>> nestedMap = list.stream()
                                                     .collect(Collectors.toMap(
                                                             Item::getName,
                                                             item -> item.getAttributes(),
                                                             (existing, replacement) -> existing
                                                     ));
    
  2. 转换为有序映射
    如果需要保持键的顺序,可以使用 LinkedHashMap

    Map<String, Item> map = list.stream()
                               .collect(Collectors.toMap(
                                       Item::getName,
                                       Function.identity(),
                                       (existing, replacement) -> existing,
                                       LinkedHashMap::new
                               ));
    
  3. 转换并过滤
    在转换过程中可以过滤掉不想要的元素。

    Map<String, Item> map = list.stream()
                               .filter(item -> item.isVisible())
                               .collect(Collectors.toMap(Item::getName, Function.identity()));
    
  4. 转换并排序
    可以首先对流进行排序,然后再收集到映射中。

    Map<String, Item> map = list.stream()
                               .sorted(Comparator.comparing(Item::getName))
                               .collect(Collectors.toMap(Item::getName, Function.identity()));
    
  5. 转换为多级映射
    可以创建一个多级映射,其中每个项映射到另一个映射。

    Map<String, Map<String, List<Item>>> multiLevelMap = list.stream()
                                                             .collect(Collectors.groupingBy(
                                                                     Item::getCategory,
                                                                     Collectors.groupingBy(Item::getName)
                                                             ));
    
  6. 转换为自定义收集器
    使用 Collectors.collectingAndThen 进行转换后进一步处理。

    Map<String, Item> map = list.stream()
                               .collect(Collectors.collectingAndThen(
                                       Collectors.toMap(Item::getName, Function.identity()),
                                       map -> map.entrySet().stream()
                                                   .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
                               ));
    
  7. 转换并应用复杂的业务逻辑
    可以在转换过程中应用复杂的业务逻辑。

    Map<String, String> map = list.stream()
                                  .collect(Collectors.toMap(
                                          Item::getName,
                                          item -> performComplexOperation(item),
                                          (existing, replacement) -> existing
                                  ));
    

在上述示例中,Item 是一个假设的类,它具有 getNamegetAttributesisVisiblegetCategory 等方法。performComplexOperation 是一个假设的函数,代表一些复杂的业务逻辑。

请注意,Collectors.toMap 中的合并函数 (existing, replacement) -> existing 用于解决键冲突,这里简单地选择了保留现有项。在实际应用中,这个函数可能会根据具体需求进行不同的处理。

这些操作展示了如何使用 Stream API 进行灵活的列表到映射的转换,包括一些复杂的业务逻辑处理。在实际编程中,你可能需要根据具体需求调整这些操作。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 8中,可以使用StreamList进行分组,并将结果换为Map。下面是一个示例代码: ```java import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class GroupingExample { public static void main(String[] args) { // 假设有一个Person类,包含name和age属性 List<Person> personList = List.of( new Person("Alice", 25), new Person("Bob", 30), new Person("Alice", 35), new Person("Charlie", 40) ); // 使用Stream的groupingBy方法进行分组,并将结果换为Map Map<String, List<Person>> personMap = personList.stream() .collect(Collectors.groupingBy(Person::getName)); // 打印分组结果 personMap.forEach((name, group) -> { System.out.println(name + ": " + group); }); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 在上述示例中,我们首先定义了一个Person类,包含name和age属性。然后,我们创建了一个包含Person对象的List。 接下来,在使用Stream的`groupingBy`方法时,我们传递了一个函数`Person::getName`作为分组的依据,它将根据Person对象的name属性进行分组。最后,通过`collect(Collectors.groupingBy())`将分组结果换为Map。 最后,我们使用`forEach`方法遍历Map,并打印分组结果。输出结果如下: ``` Alice: [Person{name='Alice', age=25}, Person{name='Alice', age=35}] Bob: [Person{name='Bob', age=30}] Charlie: [Person{name='Charlie', age=40}] ``` 以上是一个简单的示例,你可以根据自己的需求进行适当的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值