[JAVA] Stream intermediate processing

Stream generation process The part that gives various processing to the Stream generated in.

Here, we do not generate List or output it as a character string yet. In this article, as an example, let all termination process regenerate List.

map It is used when you want to convert an element using a lambda expression or function.

//Lambda expression
List<Integer> actual = list.stream().map(s->s.length()).collect(Collectors.toList());

//Method reference
List<Integer> actual = list.stream().map(String::length).collect(Collectors.toList());

filter Used when you want to narrow down the elements of Stream by a conditional expression

List<String> actual = list.stream().filter(s -> s.equals("b")).collect(Collectors.toList());

distinct Delete duplicate elements

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

List<String> actual = list.stream().distinct().collect(Collectors.toList());

// a,d,c

peek Used when you want to perform processing that does not affect the elements of Stream itself

List<String> actual = list.stream().peek(System.out::println).collect(Collectors.toList());

Sorted Use when you want to sort literally

//ascending order
List<String> actual = list.stream().sorted().collect(Collectors.toList());

//descending order
List<String> actual =list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

skip It is used when you want to get from the nth element. Note that the elements before that are discarded.

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

list.stream().skip(2).peek(System.out::println).collect(Collectors.toList());

// c,d,e

limit Used when you want to get n from the beginning

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

list.stream().limit(3).peek(System.out::print).collect(Collectors.toList());

/// a,b,c

list.stream().skip(2).limit(2).peek(System.out::print).collect(Collectors.toList());

// c,d

Recommended Posts

Stream intermediate processing
[Java] Stream API --Stream intermediate processing
[Java] Stream processing
[Java] Stream API --Stream termination processing
[Java] Stream API intermediate operation
Basic processing flow of java Stream
Data processing using stream API from Java 8
Stream play
Loop processing
Stream termination
Iterative processing
Memo Stream