Coleccionistas en detalle

Métodos de recopiladores en java8:

Directorio de artículos

 

toCollection

Esta función devuelve un recopilador, que acumula los elementos de entrada en una colección.


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");

// toCollection()
Collection<String> strCollection = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));
System.out.println(strCollection); // [a, b, c]

Set<String> strSet = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet); // [a, b, c]

List<String> strList1 = strList.parallelStream().sorted(String::compareToIgnoreCase)
		.collect(Collectors.toCollection(ArrayList::new));
System.out.println(strList1); // [a, a, b, b, c]

Listar()

Devuelve un colector que acumula los elementos de entrada en una nueva lista.


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");

List<String> uppercaseList = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(uppercaseList); // [A, B, C, B, A]

List<String> uppercaseUnmodifiableList = strList.parallelStream().map(String::toUpperCase)
		.collect(Collectors.toUnmodifiableList());
System.out.println(uppercaseUnmodifiableList); // [A, B, C, B, A]

  •  

toSet ()


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");

Set<String> uppercaseSet = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toSet());
System.out.println(uppercaseSet); // [A, B, C]

Set<String> uppercaseUnmodifiableSet = strList.parallelStream().map(String::toUpperCase)
		.collect(Collectors.toUnmodifiableSet());
System.out.println(uppercaseUnmodifiableSet); // [A, B, C]

para asignar

Mapa para generar mapa

Map<String, String> map = Stream.of("a", "b", "c")
		.collect(Collectors.toMap(Function.identity(), String::toUpperCase));
System.out.println(map); // {a=A, b=B, c=C}

// Duplicate Keys will throw: Exception in thread "main"
// java.lang.IllegalStateException: Duplicate key a (attempted merging values A
// and A)
Map<String, String> mapD = Stream.of("a", "b", "c", "b", "a")
		.collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat));
System.out.println(mapD); // {a=AA, b=BB, c=C}

// above are HashMap, use below to create different types of Map
TreeMap<String, String> mapTree = Stream.of("a", "b", "c", "b")
		.collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat, TreeMap::new));
System.out.println(mapTree); {a=A, b=BB, c=C}

unión

Cadena de conexión


String concat = Stream.of("a", "b").collect(Collectors.joining());
System.out.println(concat); // ab

String csv = Stream.of("a", "b").collect(Collectors.joining(","));
System.out.println(csv); // a,b

String csv1 = Stream.of("a", "b").collect(Collectors.joining(",", "[", "]"));
System.out.println(csv1); // [a,b]

String csv2 = Stream.of("a", new StringBuilder("b"), new StringBuffer("c")).collect(Collectors.joining(","));
System.out.println(csv2); // a,b

mapeo / mapeo plano

Aplica la función a los elementos de entrada y luego los acumula en el colector dado


Set<String> setStr = Stream.of("a", "a", "b")
		.collect(Collectors.mapping(String::toUpperCase, Collectors.toSet()));
System.out.println(setStr); // [A, B]

Set<String> setStr1 = Stream.of("a", "a", "b")
		.collect(Collectors.flatMapping(s -> Stream.of(s.toUpperCase()), Collectors.toSet()));
System.out.println(setStr1); // [A, B]

filtración

Establecer criterios de filtrado


List<String> strList2 = Lists.newArrayList("1", "2", "10", "100", "20", "999");
Set<String> set = strList2.parallelStream()
		.collect(Collectors.filtering(s -> s.length() < 2, Collectors.toSet()));
System.out.println(set); // [1, 2]

recolectando y luego

Devuelve un colector que acumula los elementos de entrada en el colector dado y luego realiza otras funciones de finalización

List<String> strList2 = Lists.newArrayList("1", "2", "10", "100", "20", "999");

List<String> unmodifiableList = strList2.parallelStream()
		.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
System.out.println(unmodifiableList); // [1, 2, 10, 100, 20, 999]

contando

contar


Long evenCount = Stream.of(1, 2, 3, 4, 5).filter(x -> x % 2 == 0).collect(Collectors.counting());
System.out.println(evenCount); // 2

mi ciudad

Devuelve el elemento más pequeño de acuerdo con el comparador dado


Optional<Integer> min = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> x - y));
System.out.println(min); // Optional[1]

maxBy

Devuelve el elemento más grande según el comparador dado.

Optional<Integer> max = Stream.of(1, 2, 3, 4, 5).collect(Collectors.maxBy((x, y) -> x - y));
		System.out.println(max); // Optional[5]

summingInt / summingLong / summingDouble

Suma

List<String> strList3 = Arrays.asList("1", "2", "3", "4", "5");
Integer sum = strList3.parallelStream().collect(Collectors.summingInt(Integer::parseInt));
System.out.println(sum); // 15

Long sumL = Stream.of("12", "23").collect(Collectors.summingLong(Long::parseLong));
System.out.println(sumL); // 35

Double sumD = Stream.of("1e2", "2e3").collect(Collectors.summingDouble(Double::parseDouble));
System.out.println(sumD); // 2100.0

averagingInt / averagingLong / averagingDouble

Promedio

List<String> strList4 = Arrays.asList("1", "2", "3", "4", "5");
Double average = strList4.parallelStream().collect(Collectors.averagingInt(Integer::parseInt));
System.out.println(average); // 3.0

Double averageL = Stream.of("12", "23").collect(Collectors.averagingLong(Long::parseLong));
System.out.println(averageL); // 17.5

Double averageD = Stream.of("1e2", "2e3").collect(Collectors.averagingDouble(Double::parseDouble));
System.out.println(averageD); // 1050.0

groupingBy

Agrupamiento

Map<Integer, List<Integer>> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.groupingBy(x -> x * 10));
System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}

groupingByConcurrent

La agrupación es concurrente y desordenada

Map<Integer, List<Integer>> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.groupingByConcurrent(x -> x * 10));
System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}

particionamiento por

Devuelve un recopilador, que divide los elementos de entrada de acuerdo con el predicado y los organiza en el mapa <booleano, lista>.


Map<Boolean, List<Integer>> mapPartitionBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy(x -> x % 2 == 0));
System.out.println(mapPartitionBy); // {false=[1, 3, 5, 3], true=[2, 4, 4]}

BinaryOperator

Devuelve un colector que realiza la reducción de sus elementos de entrada bajo el BinaryOperator especificado. Esto se utiliza principalmente para la reducción de varios niveles, como el uso de los métodos groupingBy () y partitioningBy () para especificar colectores posteriores


Map<Boolean, Optional<Integer>> reducing = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy(
		x -> x % 2 == 0, Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Integer::intValue)))));
System.out.println(reducing); // {false=Optional[5], true=Optional[4]}

resumiendo

Estadísticas de retorno: mínimo, máximo, promedio, recuento, suma


IntSummaryStatistics summarizingInt = Stream.of("12", "23", "35")
    .collect(Collectors.summarizingInt(Integer::parseInt));
System.out.println(summarizingInt);
//IntSummaryStatistics{count=3, sum=70, min=12, average=23.333333, max=35}

Enlaces relacionados:

Explicación detallada del nuevo método de mapa en
java8 Uso de Stream en
Java8 Nuevo método de
recopilación en java8 Método detallado del uso de recopiladores en
java8 Ejemplos de interfaces funcionales de uso común en
java8 Referencias de método y referencias de constructor en
java8 Collectors.grouping
java8 API de fecha y hora de uso opcional
en java8

Supongo que te gusta

Origin blog.csdn.net/qq_37557563/article/details/110131996
Recomendado
Clasificación