Java Stream API in 5 minutes

This article is intended for people who can't read the Java Stream API.

Recommended for the following people

--I used to write Java, but I haven't written it recently --I quit coding because I couldn't read the Stream API ――I just want to know the point because I don't have time anyway

At first

The Java Stream API has nothing to do with I / O classes such as InputStream and OutputStream. A mechanism that processes a collection object such as List or Set, or a loopable element such as an array only once in a loop.

The following two points are often used when using the Stream API.

--Convert entity (map method) --Filter the collection (filter method)

Here is the Java code.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamTest {
    public static void main(String[] args) {
        List<String> csvList = new ArrayList<>();
        csvList.add("Naoki Tanaka,MAN");
        csvList.add("Kazuki Kitamura,MAN");
        csvList.add("Shizuka Kato,WOMAN");
        csvList.add("Ono no Imoko,UNKNOWN");
        // 1.Convert an entity.(map)
        List<Person> persons = csvList.stream().map(Person::convertPersonFromCSV).collect(Collectors.toList());

        // 2.Filter entities.(filter)
        List<Person> mens = persons.stream().filter(p -> p.getGender() == Gender.MAN).collect(Collectors.toList());

        System.out.println("Print all persons");
        persons.forEach(System.out::println);

        System.out.println("Print mens only");
        mens.forEach(p -> System.out.println(p.getName()));
    }

    enum Gender {
        MAN,
        WOMAN,
        UNKNOWN;
    }

    static class Person {
        private String name;
        private Gender gender;

        public Person(String name, Gender gender) {
            this.name = name;
            this.gender = gender;
        }

        @Override
        public String toString() {
            return String.format("My name is %s . \r\nMy gender is %s.", name, gender);
        }

        public String getName() {
            return this.name;
        }

        public Gender getGender() {
            return this.gender;
        }

        public static Person convertPersonFromCSV(String csv) {
            String[] csvStrings = csv.split(",");
            if (csvStrings.length != 2) throw new IllegalArgumentException("csv is illegal format.");
            return new Person(csvStrings[0], Gender.valueOf(csvStrings[1]));
        }
    }
}

Let's look at the above in order

Convert an entity

When converting an entity, use the map method. Use the map method to convert, and the collect method to convert Stream to Collection type again. </ b>

There are three main ways to write:

csvList.stream().map(Person::convertPersonFromCSV).collect(Collectors.toList());
csvList.stream().map(csv -> Person.convertPersonFromCSV(csv)).collect(Collectors.toList());
csvList.stream().map(csv -> {
                         Person person = Person.convertPersonFromCSV(csv);
                         return person;
                     }).collect(Collectors.toList());

Everything is the same, get the String that is an element of csvList, I am executing a method that converts it to a Person object and returns it.

--The first is how to write by omitting the csv argument --The second is how to write in one line, omitting the return method ――The third is how to write without omitting anything

By using Stream, I was able to convert List to List in one line (one liner). </ b> One of the advantages of using Stream is that you can reduce the amount of code you write.

If you don't have time, please skip the following.

  • csvList.stream() --Get a Stream object.
  • map(Person::convertPersonFromCSV) --String, which is the Generic interface of csvList, is given as an argument of the map method. --Call the entity conversion method of Person class to convert entity and return entity class. --Using the method that implements the Function interface, the String class is converted to the Person class and returned.
  • collect(Collectors.toList()) --Collect the converted Persons. --Add to the List class with Collectors.toList (). --You can also convert it to Set or Map with Collectors.toXXX (). In the case of toMap, you need to write two Functions that return key and value. --The order of method processing is an image that repeats the process of "converting with map and storing objects processed with Stream with collect in a list".

Filter the collection

You can create a new collection object by excluding certain elements from the collection. </ b> Use the filter method to describe the object you want to keep.

persons.stream().filter(p -> p.getGender() == Gender.MAN).collect(Collectors.toList());

By using Stream, I was able to create a new collection with only men extracted from List in one liner. </ b>

  • filter(p -> p.getGender() == Gender.MAN) --Take Person as an argument and return boolean.

Other things you often do with the Stream API

  • findAny --In combination with filter, detect if a particular element is present.
  • sum --Calculate the total number of collections in combination with mapToInt.
  • reduce --Combine the elements of the collection into one object.

Recommended Posts