📜  Java8 Collection类

📅  最后修改于: 2020-10-13 03:32:34             🧑  作者: Mango

Java收集器

收集器是扩展Object类的最终类。它提供归约操作,例如将元素累积到集合中,根据各种标准对元素进行汇总等。

Java Collectors类提供了各种处理元素的方法

Methods Description
public static Collector averagingDouble(ToDoubleFunction mapper) It returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements. If no elements are present, the result is 0.
public static Collector reducing(T identity, BinaryOperator op) It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.
public static Collector> reducing(BinaryOperator op) It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator. The result is described as an Optional.
public static Collector reducing(U identity, Function mapper, BinaryOperator op) It returns a Collector which performs a reduction of its input elements under a specified mapping function and BinaryOperator. This is a generalization of reducing(Object, BinaryOperator) which allows a transformation of the elements before reduction.
public static Collector>> groupingBy(Function classifier) It returns a Collector implementing a “group by” operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.
public static Collector> groupingBy(Function classifier, Collector downstream) It returns a Collector implementing a cascaded “group by” operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.
public static > Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream) It returns a Collector implementing a cascaded “group by” operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. The Map produced by the Collector is created with the supplied factory function.
public static Collector>> groupingByConcurrent(Function classifier) It returns a concurrent Collector implementing a “group by” operation on input elements of type T, grouping elements according to a classification function.
public static Collector> groupingByConcurrent(Function classifier, Collector downstream) It returns a concurrent Collector implementing a cascaded “group by” operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.
public static > Collector groupingByConcurrent(Function classifier, Supplier mapFactory, Collector downstream) It returns a concurrent Collector implementing a cascaded “group by” operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. The ConcurrentMap produced by the Collector is created with the supplied factory function.
public static Collector>> partitioningBy(Predicate predicate) It returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map>. There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.
public static Collector> partitioningBy(Predicate predicate, Collector downstream) It returns a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to another Collector, and organizes them into a Map whose values are the result of the downstream reduction.
public static Collector> toMap(Function keyMapper,
Function valueMapper)
It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
public static Collector> toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
public static > Collector toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier) It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
public static Collector> toConcurrentMap(Function keyMapper, Function valueMapper) It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.
public static Collector> toConcurrentMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.
public static > Collector toConcurrentMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier) It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.
public static Collector summarizingInt(ToIntFunction mapper) It returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.
public static Collector summarizingLong(ToLongFunction mapper) It returns a Collector which applies an long-producing mapping function to each input element, and returns summary statistics for the resulting values.
public static Collector summarizingDouble(ToDoubleFunction mapper) It returns a Collector which applies an double-producing mapping function to each input element, and returns summary statistics for the resulting values.

Java收集器示例:以列表形式获取数据

import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Product{
int id;
String name;
float price;

public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class CollectorsExample {
public static void main(String[] args) {
List productsList = new ArrayList();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
List productPriceList = 
productsList.stream()
.map(x->x.price)// fetching price
.collect(Collectors.toList());// collecting as list
System.out.println(productPriceList);
}
}

输出:

[25000.0, 30000.0, 28000.0, 28000.0, 90000.0]

Java收集器示例:将数据转换为一组

import java.util.stream.Collectors;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
classProduct{
intid;
String name;
floatprice;

public Product(intid, String name, floatprice) {
this.id = id;
this.name = name;
this.price = price;
}
}
publicclass CollectorsExample {
publicstaticvoid main(String[] args) {
ListproductsList = new ArrayList();
//Adding Products
productsList.add(newProduct(1,"HP Laptop",25000f));
productsList.add(newProduct(2,"Dell Laptop",30000f));
productsList.add(newProduct(3,"Lenevo Laptop",28000f));
productsList.add(newProduct(4,"Sony Laptop",28000f));
productsList.add(newProduct(5,"Apple Laptop",90000f));
SetproductPriceList = 
productsList.stream()
.map(x->x.price)// fetching price
.collect(Collectors.toSet());// collecting as list
System.out.println(productPriceList);
}
}

输出:

[25000.0, 30000.0, 28000.0, 90000.0]

Java收集器示例:使用sum方法

import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Product{
int id;
String name;
float price;

public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class CollectorsExample {
public static void main(String[] args) {
List productsList = new ArrayList();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
Double sumPrices = 
productsList.stream()
.collect(Collectors.summingDouble(x->x.price));// collecting as list
System.out.println("Sum of prices: "+sumPrices);
Integer sumId = 
productsList.stream().collect(Collectors.summingInt(x->x.id));
System.out.println("Sum of id's: "+sumId);
}
}

输出:

Sum of prices: 201000.0
Sum of id's: 15

Java收集器示例:获取产品平均价格

import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Product{
int id;
String name;
float price;

public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class CollectorsExample {
public static void main(String[] args) {
List productsList = new ArrayList();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
Double average = productsList.stream()
 .collect(Collectors.averagingDouble(p->p.price));
System.out.println("Average price is: "+average);
}
}

输出:

Average price is: 40200.0

Java收集器示例:计数元素

import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Product{
intid;
String name;
floatprice;

public Product(intid, String name, floatprice) {
this.id = id;
this.name = name;
this.price = price;
}
publicint getId() {
returnid;
}
public String getName() {
returnname;
}
publicfloat getPrice() {
returnprice;
}
}
publicclass CollectorsExample {
publicstaticvoid main(String[] args) {
ListproductsList = new ArrayList();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
Long noOfElements = productsList.stream()
   .collect(Collectors.counting());
System.out.println("Total elements : "+noOfElements);
}
}

输出:

Total elements : 5