JDK1. 8 new feature (2): collectors collector class

I What are collectors?

Java 8 API adds a new abstraction called stream. We can easily manipulate stream objects with the help of stream API.

There are two methods, collect and collectionandthen, in stream. You can aggregate the data in the stream with the help of the collectors collector class, such as accumulating elements into the collection, and summarizing and classifying elements according to various standards.

II for instance?

//获取String集合
List<String> strings = Arrays.asList("ab","","bc","cd","abcd","jkl");
//通过stream操作集合
List<String> stringList = strings.stream()
    //为集合中的每一个元素拼接“???”
    .map(s -> s += "???")
    //返回集合
    .collect(Collectors.toList());

As shown in the code, we can easily aggregate the processed stream data through the collectors class, including but not limited to converting the processed stream into a collection

III How do I use collectors?

1. Methods provided in the collectors class

To sum up, there are the following methods:

1.1 convert to set: tolist(), toset(), tomap(), tocollection()

1.2 split and splice the set into a string: joining()

1.3 maximum, minimum, sum and average: maxby(), minby(), summingint(), averagedouble()

1.4 grouping sets: groupingby(), partitioningby()

1.5 mapping data: mapping ()

2. Collectors class method source code

public final class Collectors {

    // 转换成集合
    public static <T> Collector<T,?,List<T>> toList();
    public static <T> Collector<T,Set<T>> toSet();
    public static <T,K,U> Collector<T,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,Function<? super T,? extends U> valueMapper);
    public static <T,C extends Collection<T>> Collector<T,C> toCollection(supplier<C> collectionFactory);

    // 拼接字符串,有多个重载方法                                  
    public static Collector<CharSequence,String> joining(CharSequence delimiter);   
    public static Collector<CharSequence,String> joining(CharSequence delimiter,CharSequence prefix,CharSequence suffix);      
    // 最大值、最小值、求和、平均值                                                         
    public static <T> Collector<T,Optional<T>> maxBy(Comparator<? super T> comparator);
    public static <T> Collector<T,Optional<T>> minBy(Comparator<? super T> comparator);
    public static <T> Collector<T,Integer> summingInt(ToIntFunction<? super T> mapper);      
    public static <T> Collector<T,Double> averagingDouble(ToDoubleFunction<? super T> mapper);                   

    // 分组:可以分成true和false两组,也可以根据字段分成多组                                 
    public static <T,K> Collector<T,List<T>>> groupingBy(Function<? super T,? extends K> classifier);
    // 只能分成true和false两组
    public static <T> Collector<T,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate);

    // 映射
    public static <T,U,A,R> Collector<T,R> mapping(Function<? super T,? extends U> mapper,Collector<? super U,R> downstream);

    public static <T,U> reducing(U identity,BinaryOperator<U> op);
}

IV example

//接下来的示例代码基于此集合
List<String> strings = Arrays.asList("ab","s","sd","jkl");

1. Convert stream data into sets

//转换成list集合
List<String> stringList = strings.stream().collect(Collectors.toList());

//转换成Set集合
Set<String> stringSet = strings.stream().collect(Collectors.toSet());

//转换成Map集合
Map<String,Object> stringObjectMap = strings.stream()
    .collect(Collectors.toMap(k -> k,v -> v ));

System.out.println(stringList);
System.out.println(stringSet);
System.out.println(stringObjectMap);

//=================打印结果=================
[ab,s,bc,cd,abcd,sd,jkl]
[ab,jkl,abcd]
{sd=sd,cd=cd,bc=bc,ab=ab,s=s,jkl=jkl,abcd=abcd}

2. Split and splice the set into strings

//joining
String str1 = strings.stream()
    .collect(Collectors.joining("--"));

//collectingAndThen
String str2 = strings.stream()
    .collect(Collectors.collectingAndThen(
        //在第一个joining操作的结果基础上再进行一次操作
        Collectors.joining("--"),s1 -> s1 += ",then"
    ));

System.out.println(str1);
System.out.println(str2);

//=================打印结果=================
ab--s--bc--cd--abcd--sd--jkl
ab--s--bc--cd--abcd--sd--jkl,then

3. Maximum, minimum, sum and average

List<Integer> list = Arrays.asList(1,2,3,4,5);

//最大值
Integer maxValue = list.stream().collect(Collectors.collectingAndThen(
    //maxBy需要Comparator.comparingInt来确定排序规则
    Collectors.maxBy(Comparator.comparingInt(a -> a)),Optional::get
));
//最小值
Integer minValue = list.stream().collect(Collectors.collectingAndThen(
    //minBy需要Comparator.comparingInt来确定排序规则
    Collectors.minBy(Comparator.comparingInt(a -> a)),Optional::get
));
//求和
Integer sumValue = list.stream().collect(Collectors.summingInt(i -> i));
//平均值
Double avgValue = list.stream().collect(Collectors.averagingDouble(i -> i));

System.out.println("列表中最大的数 : " + maxValue);
System.out.println("列表中最小的数 : " + minValue);
System.out.println("所有数之和 : " + sumValue);
System.out.println("平均数 : " + avgValue);

//=================打印结果=================
列表中最大的数 : 5
列表中最小的数 : 1
所有数之和 : 15
平均数 : 3.0

Although this is OK, intsummarystatistics is obviously more flexible

4. Group sets

Map<Integer,List<String>> map = strings.stream()
    //根据字符串长度分组(同理,对对象可以通过某个属性分组)
    .collect(Collectors.groupingBy(String::length));

Map<Boolean,List<String>> map2 = strings.stream()
    //根据字符串是否大于2分组
    .collect(Collectors.groupingBy(s -> s.length() > 2));

System.out.println(map);
System.out.println(map2);

//=================打印结果=================
{1=[s],2=[ab,sd],3=[jkl],4=[abcd]}
{false=[ab,true=[abcd,jkl]}

5. Map data

String str = strings.stream().collect(Collectors.mapping(
    //先对集合中的每一个元素进行映射操作
    s -> s += ",mapping",//再对映射的结果使用Collectors操作
    Collectors.collectingAndThen(Collectors.joining(";"),s -> s += "=====then" )
));

System.out.println(str);

//=================打印结果=================
ab,mapping;s,mapping;bc,mapping;cd,mapping;abcd,mapping;sd,mapping;jkl,mapping=====then
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>