Java Stream Collectors的toList()、toSet()、toCollection()和toMap()的使用

简介:

Stream是Java 8的新特性,基于lambda表达式,是对集合对象功能的增强,它专注于对集合对象进行各种高效、方便聚合操作或者大批量的数据操作,提高了编程效率和代码可读性。Collectors通常在Stream处理后,返回转换成集合类时使用,本文主要介绍Java Stream中Collectors.toList()、Collectors.toSet()、Collectors.toCollection()和Collectors.toMap()的使用,以及相关的示例代码。

1、Collectors.toList()的使用
Collectors.toList()是将Stream转换成List,List为ArrayList,需要转换成其它,则需要使用Collectors.toCollection(),例如,

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
   public static class Person {
     int age;
     Person (int age) {
         this.age = age;
     }
     public int getAge() {
         return age;
     }
     public void setAge(int age) {
         this.age = age;
     }

  }
public static void main(String[] args) {

    List<Person> pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
    List<Person> result = pList.stream()
                                .map(o -> {
                            o.setAge(18);
                            return o;
                        }).collect(Collectors.toList());

    System.out.println("stream() result :"+result.getClass());
    System.exit(0); //success
  }
}

2、Collectors.toSet()的使用
Collectors.toSet()是将Stream转换成Set,Set为HashSet,需要转换成其它,则也需要使用Collectors.toCollection(),例如,

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
   public static class Person {
     int age;
     Person (int age) {
         this.age = age;
     }
     public int getAge() {
         return age;
     }
     public void setAge(int age) {
         this.age = age;
     }

  }
public static void main(String[] args) {

    List<Person> pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
    Set<Person> setResult = pList.stream()
                                .map(o -> {
                            o.setAge(18);
                            return o;
                        }).collect(Collectors.toSet());

    System.out.println("stream() result :"+setResult.getClass());
    System.exit(0); //success
  }
}

3、Collectors.toCollection()的使用
toList()toSet()使用时,需要转换成指定的集合类型,则可以使用Collectors.toCollection(),如下,

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
   public static class Person {
     int age;
     String name;
     Person (int age,String name) {
         this.age = age;
         this.name = name;
     }
     public int getAge() {
         return age;
     }
     public void setAge(int age) {
         this.age = age;
     }
     public String getName() {
         return name;
     }
     public void setName(String name) {
         this.name = name;
     }

  }
public static void main(String[] args) {

    List<Person> pList = Arrays.asList(new Person(11,"mike"),new Person(22,"lynn"), new Person(33,"john"), new Person(44,"mickey"), new Person(55,"fiona"));
    List<Person> listResult = pList.stream().collect(Collectors.toCollection(LinkedList::new));
    System.out.println("stream() result :"+listResult.getClass());
    System.exit(0); //success
  }
}

4、Collectors.toMap()的使用
Collectors.toMap()是将Stream转换成Map,Map为HashMap,需要转换成其它,则也需要使用Collectors.toCollection()
例如,

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
   public static class Person {
     int age;
     String name;
     Person (int age,String name) {
         this.age = age;
         this.name = name;
     }
     public int getAge() {
         return age;
     }
     public void setAge(int age) {
         this.age = age;
     }
     public String getName() {
         return name;
     }
     public void setName(String name) {
         this.name = name;
     }

  }
public static void main(String[] args) {

    List<Person> pList = Arrays.asList(new Person(11,"mike"),new Person(22,"lynn"), new Person(33,"john"), new Person(44,"mickey"), new Person(55,"fiona"), new Person(31,"fiona"));
    //(oldValue, newValue) -> newValue是重复key时,使用的值,可以指定
    Map<String, Integer> map = pList.stream().collect(Collectors.toMap(Person::getName, Person::getAge,(oldValue, newValue) -> newValue));
    System.out.println("stream() result :"+map);
    System.out.println("stream() result :"+map.getClass());
    //指定转换成集合类型LinkedHashMap
    Map<String, Integer> map1 = pList.stream().collect(Collectors.toMap(Person::getName, Person::getAge,(oldValue, newValue) -> newValue,LinkedHashMap::new));
    System.out.println("stream() result :"+map1);
    System.out.println("stream() result :"+map1.getClass());
    System.exit(0); //success
  }
}

了解更多分析及数据抓取可查看:
http://data.yisurvey.com:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Collectors.toMapCollectors.mapping都是Java 8中的流操作工具类Collectors的方法,用于对流中的元素进行收集和转换。 Collectors.toMap方法用于将流中的元素映射为键值对,并将其收集到一个Map中。它接受两个参数,第一个参数是用于提取键的函数,第二个参数是用于提取值的函数。如果流中存在重复的键,则会抛出一个IllegalStateException异常。 而Collectors.mapping方法则是在收集元素到Map时,对元素进行进一步的转换操作。它接受两个参数,第一个参数是用于提取键的函数,第二个参数是用于对值进行转换的函数。它可以与其他收集器一起使用,例如Collectors.toListCollectors.toSet,来对值进行进一步的收集和转换。 下面是一个示例代码,演示了如何使用Collectors.toMapCollectors.mapping方法: ```java import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> fruits = Arrays.asList("apple", "banana", "orange"); // 使用Collectors.toMap将水果列表转换为以长度为键,水果名称为值的Map Map<Integer, String> lengthToNameMap = fruits.stream() .collect(Collectors.toMap(String::length, fruit -> fruit)); System.out.println(lengthToNameMap); // 使用Collectors.mapping将水果列表转换为以长度为键,水果名称列表为值的Map Map<Integer, List<String>> lengthToNamesMap = fruits.stream() .collect(Collectors.groupingBy(String::length, Collectors.mapping(fruit -> fruit, Collectors.toList()))); System.out.println(lengthToNamesMap); } } ``` 输出结果为: ``` {5=apple, 6=orange, 6=banana} {5=[apple], 6=[orange, banana]} ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值