List processing to understand with pictures --java8 stream / javaslang-

I often hear "I tried stream with java8 but I'm not used to it" or "I can't do it if I try to do something a little difficult", so I'll summarize it.

If you grasp the type, it seems that you know 80%, so I will try to make it a picture.

~~ By the way, the article is long, but it's enough to read the first [main story - headline! ~~

It's too long to think calmly, so I divided it.

[Main story --java8 stream]: filter, map, reduce

Let's hold down the basic three hands.

You may not be familiar with reduce, but it's aMapReduce model advocated by Google, so it's talked about with map. -> wiki

Let's look at it using the example below.

/*
 *There is the following log
 *Label or label:Output line by line in millisec format
 *
 *Find the sum of milliseconds
 */
List<String> lines = Arrays.asList(
    "application-boot", "access-dispatch:10", "dispatched", "authentication:30", "database-access:45", "response-creation:15", "access-logging"
);

The important thing is the type anyway, so don't be afraid of generics and just check it.

Then, a lot of such pictures will come out.

legend.png

ʻA-> B fis written in java code asB f (a);, and ʻA and B are String and ʻOptional . Contains a specific type such as `. In other words, it's Generics.

filter The definition of filter is as follows.

Stream<T> filter(Predicate<? super T> predicate);

Forget about Predicate <T>, which means "argument is T and return value is bool", and ? Super T.

Let's take the type notation of Predicate <T> as T to bool and write(T-> bool). By the way, let's simplify Generics as well.

Stream<T> filter((T -> bool) f);

To use filter to make lines only lines with :, you can write:

lines.stream()
        .filter(line -> line.contains(":"))                  // ["access-dispatch:10", "authentication:30", "database-access:45", "response-creation:15"]

If you write the definition as T-> bool, the implementationline-> line.contains (":")looks the same. (In this subject, T is specifically String)

Is it like this when drawn in a picture?

filter.png

filter means that the ** type ** does not change, but the ** number ** changes.

map Here is the definition of map.

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

This is also simplified in the same way.

Stream<R> map((T -> R) f);

Using map to make the line of label: millisec ʻInteger can be written after filter` as follows.

lines.stream()
        .filter(line -> line.contains(":"))                  // ["access-dispatch:10", "authentication:30", "database-access:45", "response-creation:15"]
        .map(line -> Integer.valueOf(line.split(":")[1]))    // [10, 30, 45, 15]

Here, too, the implementation has the same shape as the definition T-> R. (In this subject, R is specifically ʻInteger, so it would be nice if T-> Rlooks likeString-> Integer`)

Is it like this when drawn in a picture?

map.png

map means that the ** number ** does not change, but the ** type ** changes.

reduce There are three definitions of reduce in java8 stream, but this is what I'm going to use now.

T reduce(T identity, BinaryOperator<T> accumulator);

BinaryOperator <T> is a little unfamiliar, but it means that "the argument is two T and the return value is T". Let's simplify this without being afraid.

T reduce(T t, ((T, T) -> T) f);

reduce is generally called" convolution "and is a process of accumulating results in order from the top of the list.

To use reduce to make a line of ʻInteger the sum of ʻInteger, you can write this after map.

lines.stream()
        .filter(line -> line.contains(":"))                  // ["access-dispatch:10", "authentication:30", "database-access:45", "response-creation:15"]
        .map(line -> Integer.valueOf(line.split(":")[1]))    // [10, 30, 45, 15]
        .reduce(0, (acc, n) -> acc + n)                      // 100

There are a few parentheses in the definition, but it should be a little easier to understand because T, (T, T)-> T and0, (acc, n)-> ...have the same shape.

Is it like this when drawn in a picture?

reduce with zero a.png

reduce is a process in which ** list elements ** become ** single result **.

Summary

This is clear!

 *Find the sum of milliseconds

Is

// (Repost)

lines.stream()
        .filter(line -> line.contains(":"))                  // ["access-dispatch:10", "authentication:30", "database-access:45", "response-creation:15"]
        .map(line -> Integer.valueOf(line.split(":")[1]))    // [10, 30, 45, 15]
        .reduce(0, (acc, n) -> acc + n)                      // 100

I solved it with.

For the time being, I will post the whole picture.

resolve.png

end

All the extras from here onwards have been separated into the following articles.

List processing understood by pictures --java8 stream / javaslang --bonus

Refreshing.

Recommended Posts

List processing to understand with pictures --java8 stream / javaslang-
List processing to understand with pictures --java8 stream / javaslang --bonus
[java8] To understand the Stream API
Java8 list conversion with Stream map
[Java] Stream processing
[Java] How to operate List using Stream API
Sample code to convert List to List <String> in Java Stream
Java to play with Function
[Java] Stream API --Stream termination processing
[Java] Stream API --Stream intermediate processing
Connect to DB with Java
Connect to MySQL 8 with Java
[Java] Introduction to Stream API
Java thread to understand loosely
How to handle exceptions coolly with Java 8 Stream or Optional
I want to make a list with kotlin and java!
Convert 2D array to csv format with Java 8 Stream API
[Java 8] Duplicate deletion (& duplicate check) with Stream
Java to learn with ramen [Part 1]
[Java] Points to note with Arrays.asList ()
[Introduction to Java] About Stream API
Delegate some Java processing to JavaScript
Dare to challenge Kaggle with Java (1)
[Java] Element existence check with Stream
[Processing × Java] How to use variables
I tried to interact with Java
[Java] Convert 1-to-N List to Map
[Java] How to use List [ArrayList]
Server processing with Java (Introduction part.1)
Surprisingly deep Java list inversion-Stream processing
Basic processing flow of java Stream
Java, arrays to start with beginners
Java 8 ~ Stream API ~ to start now
[Java] Conversion from array to List
[Processing × Java] How to use arrays
Java array / list / stream mutual conversion list
[Java] [ibatis] How to get records of 1-to-N relationship with List <Map <>>
I want to perform Group By processing with Stream (group-by-count, group-by-sum, group-by-max)
Java8 / 9 Beginners: Stream API addiction points and how to deal with them
[Java] Get List / Map elements with Iterator
Data processing using stream API from Java 8
How to compile Java with VsCode & Ant
Java reference to understand in the figure
[Java] How to compare with equals method
[Java] How to add data to List (add, addAll)
Introduction to algorithms with java --Search (depth-first search)
[Processing × Java] How to use the loop
Change List <Optional <T >> to Optional <List <T >> in Java
[Java] Map # merge is hard to understand.
[Processing × Java] How to use the class
[Processing × Java] How to use the function
Easy to trip with Java regular expressions
Introduction to algorithms with java --Search (breadth-first search)
[Java] Various methods to acquire the value stored in List by iterative processing
[Java] Understand the difference between List and Set
Challenge to deal with garbled characters with Java AudioSystem.getMixerInfo ()
[Java] From two Lists to one array list
I tried to make Basic authentication with Java
Introduction to algorithms with java --Search (bit full search)
Deploy Java web app to Azure with maven
Simple obstacle racing made with processing for Java