AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Java Collect(): collecting and processing data

PARTAGEZ

Stream Collectors are a powerful feature of the StreamJava 8 Stream API through which you can gather and process data efficiently. We explain the structure and possibilities of using Java’s Collect method.

What are the application areas of Java Collect()?

A Stream Collector can be used to create a list, set, or map from a Stream. A Stream is a sequence of elements processed one after the other. The Collector interface offers a set ofreduction operations for the pipeline data of a Stream. These are final operations that collect and bring together the results of intermediate steps.

Collectors can for example be used to filter or sort objects in a Stream. It is also possible to carry out a aggregation, for example adding numbers, grouping strings or counting elements. In addition, Collectors have functions to transform the content of a Stream into a specific structure. For example, you can convert a list into a map. Groupings help categorize items with the same characteristics or conditions. But above all, the Collectors of a Stream have the advantage of process data in parallel on multiple threads. Operations can thus be executed much more quickly and efficiently, especially for large volumes of data.

Syntax of Java Collect()

The method accepts as an argument a Collector which defines how the elements of the Stream should be collected and aggregated. A Collector is an interface which provides various methods for bringing together the elements of a Stream in a specific form, for example a list, a set or a map.

There are two types of Collect methods in Java:

  1. R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
  2. R collect(Collector collector)

The first variant has three functions as arguments:

  • to beg : creates a container that will be used for the intermediate result.
  • accumulator : calculates the final result.
  • combine : combines the results of the Stream’s parallel operations.

These predefined Collectors are already included in the standard library and can easily be imported and used.

The second variation uses a Collector as an argument and returns the result.

  • R : the type of the result
  • T : the type of elements in the Stream
  • HAS : the type of the accumulator function which records the intermediate state of the Collector operation
  • collector : executes the reduce operation

Using these variations, developers can create Custom collectors specially designed according to their requirements and offering a high level of flexibility and control over the reduction process.

Practical Examples of Using Java Collect()

Below we illustrate several functions of the “Stream.collect()” method. You should already be familiar with basic Java operators before moving on to Framework collection.

Link a list of strings

With Collect() in Java you can concatenate a list of character strings to obtain a new character string:

List<String> letters = List.of("a", "b", "c", "d", "e");

// sans la fonction combiner
StringBuilder result = letters.stream().collect(StringBuilder::new, (x, y) -> x.append(y),
      (a, b) -> a.append(",").append(b));
System.out.println(result.toString());

// avec la fonction combiner
StringBuilder result1 = letters.parallelStream().collect(StringBuilder::new, (x, y) -> x.append(y),
      (a, b) -> a.append(",").append(b));
System.out.println(result1.toString());

Java

We obtain the following result:

In the first calculation there is only one instance of StringBuilder which does not use the combine function. This is why the result obtained is “abcde”.

In the second result, we see that the combine function joins the StringBuilder instances and separates them with a comma.

Joining elements into a list via toList()

Using the “filter()” function, we can select specific elements in a list and save them to a new list with “toList()”.

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);

List<Integer> oddNumbers = numbers.stream().filter(x -> x % 2 != 0).collect(Collectors.toList());
System.out.println(oddNumbers);

Java

The new list now contains only odd numbers:

Join elements into a set using toSet()

In the same way, we can create a new set from the selected elements. In a set, the data is messy.

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);

Set<Integer> evenNumbers = numbers.parallelStream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
System.out.println(evenNumbers);

Java

The result is as follows:

Join elements into a map using toMap()

A map associated with Collect() in Java assigns a value to each key.

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);

Map<Integer, String> mapEvenNumbers = numbers.parallelStream().filter(x -> x % 2 == 0)
      .collect(Collectors.toMap(Function.identity(), x -> String.valueOf(x)));
System.out.println(mapEvenNumbers);

Java

In the result, we see that the entry, composed of even numbers, has been assigned identical values:

Combine elements into a string via joining()

The “joining()” method adds each element of the Stream in the order in which it appears and uses a separator to separate elements. The separator is specified as an argument to “joining()”. If no separator is specified, “joining()” uses the empty string “””.

jshell> String result1 = Stream.of("a", "b", "c").collect(Collectors.joining());

jshell> String result2 = Stream.of("a", "b", "c").collect(Collectors.joining(",", "{", "}"));

Java

The result is as follows:

result1 ==> "abc"
result2 ==> "{a,b,c}"

Java

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact