Java 8 Collectors 例子

Java 8 Collectors 例子转 http://www.concretepage.com/java/jdk-8/java-8-collectors-examplesjava.util.stream.Collectorsisajava8classthatimplementsthejava.util.stream.Collectorinterface.Collectorshasvariousme

大家好,欢迎来到IT知识分享网。

转 http://www.concretepage.com/java/jdk-8/java-8-collectors-examples
java.util.stream.Collectors is a java 8 class that implements the java.util.stream.Collector interface. Collectors has various methods to reduce and summarize elements of stream. Here we will discuss most of the methods and examples of Collectors class.

Collectors.averagingDouble

Collectors.averagingDouble calculates the average of stream element as double data type. It returns a Collector instance. The collect method of stream can accept the collector instance and will return the average value calculated by Collectors.averagingDouble. 


AveragingDoubleExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AveragingDoubleExample {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = Arrays.asList(1,2,3,4);
        Double result = list.stream().collect(Collectors.averagingDouble(d->d*2));
        System.out.println(result);
    }
}

Output : 5.0

Collectors.averagingInt 

Collectors.averagingInt calculates average of stream element as integer data type. 


AveragingIntExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AveragingIntExample {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = Arrays.asList(1,2,3,4);
        Double result = list.stream().collect(Collectors.averagingInt(v->v*2));
        System.out.println(result);
    }
}

Output: 5.0

Collectors.averagingLong 

Collectors.averagingLong calculates the average of stream element as long data type. 


AveragingLongExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AveragingLongExample {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = Arrays.asList(1,2,3,4);
        Double result = list.stream().collect(Collectors.averagingLong(v->v*2));
        System.out.println(result);
    }
}

Output: 5.0

Collectors.collectingAndThen 

Collectors.collectingAndThen accepts a collection and a function. In our example first we are calculating average by a calculator and then multiplying to itself by a function. 


CollectingAndThenExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectingAndThenExample {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = Arrays.asList(1,2,3,4);
        Double result = list.stream().collect(Collectors.collectingAndThen(Collectors.averagingLong(v->v*2),
                s-> s*s));
        System.out.println(result);
    }
}

Output: 25.0

Collectors.counting 

Collectors.counting counts the element in the stream. 


CountingExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CountingExample {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = Arrays.asList(1,2,3,4);
       long result=  list.stream().collect(Collectors.counting());
       System.out.println(result);
    }
}

Output: 4

Collectors.joining 

Collectors.joining joins the stream elements for a given delimiter, prefix and suffix. 


JoiningExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JoiningExample {
    
    
    public static void main(String[] args) {
    
    
       List<String> list = Arrays.asList("A","B","C","D");
       String result=  list.stream().collect(Collectors.joining(",","(",")"));
       System.out.println(result);
    }
}

Output is 
(A,B,C,D) 

Collectors.maxBy and Collectors.minBy 

Collectors.maxBy collects maximum element in stream for a given comparator. Collectors.minBy collects minimum element of a stream for a given comparator. 


MaxByMinByExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class MaxByMinByExample {
    
    
    public static void main(String[] args) {
    
    
       List<Integer> list = Arrays.asList(30,10,20,35);
       //Get Max       
       list.stream().collect(Collectors.maxBy(new MaxByMinByExample().new IntegerComp()))
               .ifPresent(i->System.out.println(i));
       //Get Min
       list.stream().collect(Collectors.minBy(new MaxByMinByExample().new IntegerComp()))
               .ifPresent(i->System.out.println(i));
    }
    class IntegerComp implements Comparator<Integer> {
    
    
        @Override
        public int compare(Integer i1, Integer i2) {
    
    
          if(i1 >=i2 ){
    
    
              return 1;
          }else{
    
    
              return -1;
          }
        }
    }
}

Output




    35
    10

Collectors.summingInt 

Collectors.summingInt adds all element of stream for integer data type. 


SummingIntExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SummingIntExample {
    
    
    public static void main(String[] args) {
    
    
       List<Integer> list = Arrays.asList(30,10,20,35);
       int result = list.stream().collect(Collectors.summingInt(i->i));
       System.out.println(result);
    }
}

Output: 95

Collectors.summingLong

Collectors.summingLong adds all element of stream for long data type. 


SummingLongExample.java




package com.concretepage.util.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SummingLongExample {
    
    
    public static void main(String[] args) {
    
    
       List<Long> list = new ArrayList<>();
       list.add((long)340);
       list.add((long)240);
       list.add((long)360);
       long result = list.stream().collect(Collectors.summingLong(l->l));
       System.out.println(result);
    }
}

Output: 940

Collectors.summingDouble

Collectors.summingDouble adds all element of stream for double data type. 


SummingDoubleExample.java




package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SummingDoubleExample {
    
    
    public static void main(String[] args) {
    
    
       List<Double> list = Arrays.asList(340.5,234.56,672.76);
       Double result = list.stream().collect(Collectors.summingDouble(d->d));
       System.out.println(result);
    }
}

Output: 1247.82

Collectors.toList

Collectors.toList collects the stream data as List for the given data type. 


ToListExample.java




package com.concretepage.util.stream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ToListExample {
    
    
    public static void main(String[] args) {
    
    
       List<String> list = Stream.of("AA","BB","CC").collect(Collectors.toList());
       list.forEach(s->System.out.println(s));
    }
}

Output




AA
BB
CC

Collectors.toSet

Collectors.toSet collects the element as set for the given data type. 


ToSetExample.java




package com.concretepage.util.stream;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ToSetExample {
    
    
    public static void main(String[] args) {
    
    
       Set<String> set = Stream.of("AA","AA","BB").collect(Collectors.toSet());
       set.forEach(s->System.out.println(s));
    }
}

Output




    AA
    BB

Collectors.toMap 

Collectors.toMap collects the stream element as Map. We need to define function to generate key and value for stream input value. 


ToMapExample.java




package com.concretepage.util.stream;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ToMapExample {
    
    
    public static void main(String[] args) {
    
    
       Map<String,String> map = Stream.of("AA","BB","CC").collect(Collectors.toMap(k->k, v->v+v));
       map.forEach((k,v)->System.out.println("key:"+k +"  value:"+v));
    }
}

Output




key:CC  value:CCCC
key:BB  value:BBBB
key:AA  value:AAAA

Collectors.mapping 

Java doc declares  
mapping() as below.




mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)
 

We need to pass 
Function and 
Collector and the method will return 
Collector instance.  
mapping() is used in multi-level reduction. Find the example. 


MappingDemo.java




package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MappingDemo {
    
    
    public static void main(String[] args) {
    
    
        List<Person> list = Person.getList();
        Map<Integer, String> nameByAge
           = list.stream().collect(Collectors.groupingBy(Person::getAge, 
        		   Collectors.mapping(Person::getName, Collectors.joining(","))));
        nameByAge.forEach((k,v)->System.out.println("Age:"+k +"  Persons: "+v));
    }	
}
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;
	}
	public static List<Person> getList() {
    
    
		List<Person> list = new ArrayList<>();
		list.add(new Person("Ram", 30));
		list.add(new Person("Shyam", 20));
		list.add(new Person("Shiv", 20));
		list.add(new Person("Mahesh", 30));
		return list;
	}
} 

Output




Age:20  Persons: Shyam,Shiv
Age:30  Persons: Ram,Mahesh

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/23927.html

(0)
上一篇 2023-09-02 19:00
下一篇 2023-09-03 13:45

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信