So I'm going to write the content of the subject This wonderful post is so easy to understand that I feel like I won't post anything again.
I tried it lightly for the time being.
List<String> list = Arrays.asList("AA", "BB", "C", "DD", "E", "FGH");
List<String> list2 = Arrays.asList("A", "B", "C", "DD", "E", "FGH");
System.out.println("For the time being, put it out without thinking");
list.stream().forEach(System.out::print);
System.out.println("\Skip n2 characters or more before issuing");
list.stream().dropWhile(str -> str.length() >= 2).forEach(System.out::print);
System.out.println("\nlist2 doesn't change anything as a result if you apply it to this guy after it starts with one character");
list2.stream().dropWhile(str -> str.length() >= 2).forEach(System.out::print);
Execution result
For the time being, put it out without thinking
AABBCDDEFGH
Skip two or more characters before issuing
CDDEFGH
list2 doesn't change anything as a result if you apply it to this guy after it starts with one character
ABCDDEFGH
The point is dropWhile, not a filter. The last until I write it myself
list2.stream().dropWhile(str -> str.length() >= 2).forEach(System.out::print);
I thought that ABCE would come out because it removes all the elements of 2 characters or more, but I wondered what it was because the result was different. Since it is a method that reads list2 from the beginning and skips it while there are two or more characters, it is not already two or more characters at the stage of the first element A, so nothing was dropped. It's natural when I think about it now.
The usage is similar, but I also tried takeWhile.
System.out.println("\ntakeWhile looks similar");
list.stream().takeWhile(str -> str.length() >= 2).forEach(System.out::print);
Execution result
takeWhile looks similar
AABB
The last one this time is Stream.ofNullable.
/* Stream.ofNullable I'll do it*/
List<String> list3 = Arrays.asList("A", "B", null, "DD", "E", "FGH");
System.out.println("\n character size");
// Stream.Example not ofNullable
try {
list3.stream().forEach(str -> System.out.println(str.length()));
} catch (NullPointerException nullpo) {
System.out.println("Nullpo as expected!");
}
// Stream.Example of ofNullable (Note, Stream.ofNullable(str)Stream.ofNullable(str.length())If you do something like that
//It will fall off with a nullpo. If the argument of ofNullable is NULL, it's just skipped.
list3.stream().flatMap(str -> Stream.ofNullable(str)).forEach(str -> System.out.println(str.length()));
Execution result
I will put out the font size
1
1
Nullpo as expected!
1
1
2
1
3
If the variable you want to use in forEach is NULL, you can skip it, so it seems convenient. It's a hassle to write flatMaps one by one, and it's so easy to use ... Also, this is a fairly appropriate example, but in reality, it is probably better to use it when the value cannot be obtained from Map as in the example of the reference article written at the beginning.
Recommended Posts