[In-house study session] Java basics-Lambda expression and Stream API- (2017/07/13)

0. Introduction


What i want to tell

Prerequisite knowledge


Reference books

Java本格入門.jpg "Introduction to Java -From the basics of modern style to object-oriented and practical libraries "Technical Review Co., Ltd.

This book is quoted unless otherwise specified.


table of contents


1. Lambda expression


What is a lambda expression?

Lambda expressions are powerful notations, as if you could pass the process itself to a method argument, etc.

List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, 3, 2, 1, 4, 5);

//Writing without lambda expression (anonymous class)
Collections.sort(list, new Comparator<Integer>() {
	@Override
	public int compare(Integer o1, Integer o2) {
		return Integer.compare(o1, o2);
	}
});

//How to write using a lambda expression
Collections.sort(list,
		(o1, o2) -> Integer.compare(o1, o2)
);

The lambda expression is just "easy to write an implementation method of an anonymous class", but when combined with the Stream API described later, it can be written in an easy-to-understand manner.


[Supplement] Anonymous class

Often used in event listener settings.

//How to write when setting a click event on Android
findViewById(R.id.hogehoge).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Processing at the time of clicking
    }
});

Use as an alternative to functional interfaces


Lambda expression basic grammar

//Lambda expression basic grammar
Collections.sort(list,
		(Integer o1, Integer o2) -> {
           return Integer.compare(o1, o2);
        }
);

//Omit argument type
Collections.sort(list,
		(o1, o2) -> {
           return Integer.compare(o1, o2);
        }
);

//Argument type, return, and curly braces omitted
Collections.sort(list,
		(o1, o2) -> Integer.compare(o1, o2)
);

Method reference

The method itself can also be assigned.

List<String> list = Arrays.asList("X", "Y", "Z");
//How to write using method references
list.forEach(System.out::println);

//How to write using a lambda expression
list.forEach(str -> System.out.println(str));

The argument of the forEach method is a functional interface called java.util.function.Consumer.


2.Stream API


What is Stream API?

The Stream API was introduced as a way to efficiently describe "stream processing" that sequentially processes large amounts of data.

List<Integer> list = Arrays.asList(100, 60, 30, 50, 70);

list.stream() //Stream instantiation
    .filter(s -> s>=70) //Intermediate operation.//Extract over 70.
    .forEach(s -> System.out.println(s)); //Termination operation.

Display TODO Stream image


Stream API features

Stream API is "API that describes What, not How".


Stream API classification

Stream API list


API to create Stream

//Create Stream from List or Set
List<Integer> list = Arrays.asList(100, 60, 30, 50, 70);
list.stream() //Stream instantiation
    .forEach(System.out::println);
    

//Create a Stream from a numeric range
IntStream.range(1, 5) //Does not include the end
    .forEach(System.out::println);

IntStream.rangeClosed(1, 5) //Including the end
    .forEach(System.out::println);


Intermediate operations on Stream

List<Integer> list = Arrays.asList(10, 6, 3, 5, 7);

//map:Replace element with another value
list.stream()
    .map(s -> s * s)
    .forEach(System.out::println);
    
//filter:Narrow down only the elements that match the conditions
list.stream()
    .filter(s -> s>=7)
    .forEach(System.out::println);

//sort:
list.stream()
    .sorted((s1,s2) -> s2 - s1) //descending order
    .forEach(System.out::println);


Termination operation for Stream

List<Integer> list = Arrays.asList(10, 6, 3, 5, 7);

//forEach:Take action on an element
list.stream()
    .forEach(System.out::println);
    
//collect:Create results
List<Integer> newList = list.stream()
    .filter(s -> s>=7)
    .collect(Collectors.toList());

//average:Returns the average(Aggregation operation)
list.stream()
    .average();


Functional language

JavaScript too. .. ..

Recommended Posts

[In-house study session] Java basics-Lambda expression and Stream API- (2017/07/13)
[In-house study session] Java exception handling (2017/04/26)
Summary of in-house newcomer study session [Java]
Nowadays Java lambda expressions and Stream API
Java Stream API
[Java] Stream API / map
Java8 Stream API practice
[In-house study session] Basics of Java annotation (2017/11/02) ~ Under construction ~
Study Java # 2 (\ mark and operator)
Java Stream API cheat sheet
Java Stream API in 5 minutes
Java8 stream, lambda expression summary
[Java] Stream API --Stream termination processing
[Java] Stream API --Stream intermediate processing
[Java] Introduction to Stream API
[Java] Stream API intermediate operation
Handle exceptions coolly with Java 8 lambda expressions and Stream API
[Milight Design In-house Study Session # 5] Read docker-compose.yml and Dockerfile line by line
[Study session memo] Java Day Tokyo 2017
I tried using Java8 Stream API
Java study # 5 (iteration and infinite loop)
Java 8 ~ Stream API ~ to start now
Java8 / 9 Beginners: Stream API addiction points and how to deal with them
Join a fun and fun programming study session!
Data processing using stream API from Java 8
Try using the Stream API in Java
Java study # 3 (type conversion and instruction execution)
[In-house study session] Introduction of "Readable Code"
Try various Java Stream API methods (now)
Notes on Java's Stream API and SQL
[Java ~ Classes and External Libraries ~] Study Memo (6)
I've reviewed Java's lambda expression, stream API, six months after I started Java.
Create API using Retrofit2, Okhttp3 and Gson (Java)
Java switch statement and break, Kotlin when expression ...
Study session memo: Kansai Java Engineers Association 8/5 --Selenium
How to use Java API with lambda expression
How to get and study java SE8 Gold
Java8 to start now ~ forEach and lambda expression ~
[For beginners] About lambda expressions and Stream API
[Java] How to operate List using Stream API
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -