Collectors

Collectors它是个工具类,提供了很多静态方法来返回Collector。通常作为Stream.collect()方法的入参,来实现更多的功能。

API分类

求平均值

static <T> Collector<T,?,Double>averagingDouble(ToDoubleFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements.

static <T> Collector<T,?,Double>averagingInt(ToIntFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements.

static <T> Collector<T,?,Double>averagingLong(ToLongFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements.

 统计

static <T> Collector<T,?,Long>counting()

Returns a Collector accepting elements of type T that counts the number of input elements.

 分组

static <T,K> Collector<T,?,Map<K,List<T>>>groupingBy(Function<? super T,? extends K> classifier)

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.

static <T,K,A,D> Collector<T,?,Map<K,D>>groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)

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.

static <T,K,D,A,M extends Map<K,D>>
Collector<T,?,M>
groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)

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.

static <T,K> Collector<T,?,ConcurrentMap<K,List<T>>>groupingByConcurrent(Function<? super T,? extends K> classifier)

Returns a concurrent Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function.

static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>>groupingByConcurrent(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)

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.

static <T,K,A,D,M extends ConcurrentMap<K,D>>
Collector<T,?,M>
groupingByConcurrent(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)

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.

 

 字符串操作

static Collector<CharSequence,?,String>joining()

Returns a Collector that concatenates the input elements into a String, in encounter order.

static Collector<CharSequence,?,String>joining(CharSequence delimiter)

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

static Collector<CharSequence,?,String>joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

Returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order.

 

 mapping

类似Stream.map()方法

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

Adapts a Collector accepting elements of type U to one accepting elements of type T by applying a mapping function to each input element before accumulation.

最值

static <T> Collector<T,?,Optional<T>>maxBy(Comparator<? super T> comparator)

Returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.

static <T> Collector<T,?,Optional<T>>minBy(Comparator<? super T> comparator)

Returns a Collector that produces the minimal element according to a given Comparator, described as an Optional<T>.

 

 分区

返回一个Map,key值为true或false,value为满足对应条件的数据。

static <T> Collector<T,?,Map<Boolean,List<T>>>partitioningBy(Predicate<? super T> predicate)

Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.

static <T,D,A> Collector<T,?,Map<Boolean,D>>partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)

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<Boolean, D> whose values are the result of the downstream reduction.

 

 规约

static <T> Collector<T,?,Optional<T>>reducing(BinaryOperator<T> op)

Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator.

static <T> Collector<T,?,T>reducing(T identity, BinaryOperator<T> op)

Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.

static <T,U> Collector<T,?,U>reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)

Returns a Collector which performs a reduction of its input elements under a specified mapping function and BinaryOperator.

 

求和

static <T> Collector<T,?,Double>summingDouble(ToDoubleFunction<? super T> mapper)

Returns a Collector that produces the sum of a double-valued function applied to the input elements.

static <T> Collector<T,?,Integer>summingInt(ToIntFunction<? super T> mapper)

Returns a Collector that produces the sum of a integer-valued function applied to the input elements.

static <T> Collector<T,?,Long>summingLong(ToLongFunction<? super T> mapper)

Returns a Collector that produces the sum of a long-valued function applied to the input elements.

 

 summarizing

返回各种SummarayStatistics对象,通过这些对象可以获取最大值、最小值、平均值、计数等。

static <T> Collector<T,?,DoubleSummaryStatistics>summarizingDouble(ToDoubleFunction<? super T> mapper)

Returns a Collector which applies an double-producing mapping function to each input element, and returns summary statistics for the resulting values.

static <T> Collector<T,?,IntSummaryStatistics>summarizingInt(ToIntFunction<? super T> mapper)

Returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

static <T> Collector<T,?,LongSummaryStatistics>summarizingLong(ToLongFunction<? super T> mapper)

Returns a Collector which applies an long-producing mapping function to each input element, and returns summary statistics for the resulting values.

 

集合转换

可以将Stream流转换成List、Map、Set集合。

static <T,C extends Collection<T>>
Collector<T,?,C>
toCollection(Supplier<C> collectionFactory)

Returns a Collector that accumulates the input elements into a new Collection, in encounter order.

static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

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.

static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)

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.

static <T,K,U,M extends ConcurrentMap<K,U>>
Collector<T,?,M>
toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

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.

static <T> Collector<T,?,List<T>>toList()

Returns a Collector that accumulates the input elements into a new List.

static <T,K,U> Collector<T,?,Map<K,U>>toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)

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.

static <T,K,U> Collector<T,?,Map<K,U>>toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)

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.

static <T,K,U,M extends Map<K,U>>
Collector<T,?,M>
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

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.

static <T> Collector<T,?,Set<T>>toSet()

Returns a Collector that accumulates the input elements into a new Set.

案例 



import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class CollectorsTest2 {
	public static void main(String[] args) {
		List<Book> list = new ArrayList<>();
		list.add(new Book("Core Java", 200,30));
		list.add(new Book("Learning Freemarker", 150, 50));
		list.add(new Book("Spring MVC", 300, 50));
//		list.add(new Book("Spring MVC", 300, 50));

		// averagingDouble方法
		ToDoubleFunction<Book> toDoubleFunction = new ToDoubleFunction<Book>() {
			@Override
			public double applyAsDouble(Book book) {
				return book.getPrice();
			}
		};

		Double averagingDouble = list.stream().collect(Collectors.averagingDouble(toDoubleFunction));
		System.out.println(averagingDouble);


		// averagingInt
		Double averagingInt = list.stream().collect(Collectors.averagingInt(Book::getCount));
		System.out.println(averagingInt);

		// averagingLong
		Double averagingLong = list.stream().collect(Collectors.averagingLong(Book::getCount));
		System.out.println(averagingLong);

		// collectingAndThen
		Integer andThen = list.stream().collect(Collectors.collectingAndThen(Collectors.groupingBy(Book::getName), map -> map.size()));
		System.out.println(andThen);

 		// `counting()`
		Long count = list.stream().collect(Collectors.counting());
		System.out.println(count);

		// groupingBy
		Map<String, List<Book>> groupingBy = list.stream().collect(Collectors.groupingBy(Book::getName));
		System.out.println(groupingBy); // {Learning Freemarker=[Book{name='Learning Freemarker', price=150.0, count=50}], Core Java=[Book{name='Core Java', price=200.0, count=30}], Spring MVC=[Book{name='Spring MVC', price=300.0, count=50}, Book{name='Spring MVC', price=300.0, count=50}]}

		Map<String, Long> groupingBy_Reduce = list.stream().collect(Collectors.groupingBy(Book::getName, Collectors.counting()));
		System.out.println(groupingBy_Reduce); // {Learning Freemarker=1, Core Java=1, Spring MVC=2}

		HashMap<String, Long> groupingBy_ResultMap_Reduce = list.stream().collect(Collectors.groupingBy(Book::getName, HashMap::new, Collectors.counting()));
		System.out.println(groupingBy_ResultMap_Reduce); // {Learning Freemarker=1, Core Java=1, Spring MVC=2}

		// groupingByConcurrent
		ConcurrentMap<String, List<Book>> concurrentGroupBy = list.stream().collect(Collectors.groupingByConcurrent(Book::getName));
		ConcurrentMap<String, Long> concurrentGroupBy_Reduce = list.stream().collect(Collectors.groupingByConcurrent(Book::getName, Collectors.counting()));
		ConcurrentHashMap<String, Long> concurrentGroupBy_ResultMap_Reduce = list.stream().collect(Collectors.groupingByConcurrent(Book::getName, ConcurrentHashMap::new, Collectors.counting()));

		// joining
		String joining = list.stream().map(Book::getName).collect(Collectors.joining(","));
		System.out.println(joining); // Core Java,Learning Freemarker,Spring MVC,Spring MVC

		// mapping
		String mapping = list.stream().collect(Collectors.mapping(Book::getName, Collectors.joining(",")));
		System.out.println(mapping); // Core Java,Learning Freemarker,Spring MVC,Spring MVC

		// maxBy
		Optional<Book> maxBy = list.stream().collect(Collectors.maxBy(Comparator.comparing(Book::getPrice)));
		maxBy.ifPresent(System.out::println); // Book{name='Spring MVC', price=300.0, count=50}

		// minBy
		Optional<String> minBy = list.stream().map(Book::getName).collect(Collectors.maxBy(String::compareTo));
		minBy.ifPresent(System.out::println); // Spring MVC

		// partitioningBy
		Map<Boolean, List<Book>> partitioningBy = list.stream().collect(Collectors.partitioningBy(book -> book.getPrice() > 200));
		System.out.println(partitioningBy); // {false=[Book{name='Core Java', price=200.0, count=30}, Book{name='Learning Freemarker', price=150.0, count=50}], true=[Book{name='Spring MVC', price=300.0, count=50}, Book{name='Spring MVC', price=300.0, count=50}]}

		Map<Boolean, Long> partitioningBy_Reduce = list.stream().collect(Collectors.partitioningBy(book -> book.getPrice() > 200, Collectors.counting()));
		System.out.println(partitioningBy_Reduce); // {false=2, true=2}

		// reducing
		Optional<Book> reducing = list.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Book::getPrice))));
		reducing.ifPresent(System.out::println); // Book{name='Spring MVC', price=300.0, count=50}

		// summarizing
		IntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(Book::getCount));
		double average = intSummaryStatistics.getAverage();
		long count1 = intSummaryStatistics.getCount();
		int max = intSummaryStatistics.getMax();
		int min = intSummaryStatistics.getMin();

		// toConcurrentMap
		ConcurrentMap<String, Integer> toConcurrentMap = list.stream().collect(Collectors.toConcurrentMap(Book::getName, Book::getCount));
		System.out.println(toConcurrentMap);

		// toList
		List<Book> toList = list.stream().collect(Collectors.toList());

		// toMap
		Map<String, Integer> toMap = list.stream().collect(Collectors.toMap(Book::getName, Book::getCount));
	}

	static class Book {
		private String name;
		private double price;
		private int count;

		public Book(String name, double price, int count) {
			this.name = name;
			this.price = price;
			this.count = count;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public double getPrice() {
			return price;
		}

		public void setPrice(double price) {
			this.price = price;
		}

		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		@Override
		public String toString() {
			return "Book{" +
					"name='" + name + '\'' +
					", price=" + price +
					", count=" + count +
					'}';
		}
	}
}

希望能帮助大家熟悉Collectors的使用。 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_中年人

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值