Do you use Stream in Java?

Java 9 Stream new features

Java 9 will add three features to Stream.

・ TakeWhile Targets data while satisfying the conditions ・ Data that meets the dropWhile condition is excluded. ・ OfNullable Allow null

But I don't think I see anyone (or source) who uses Stream at work before the new feature. (I don't have many opportunities to use new things at work)

If you don't touch new things, they will be left behind, so I took a quick look at what they were like.

When do you use Stream in the first place?

I think I will probably use it at such times.

・ Basically, you will be able to write with less description than before, so the source will be refreshed. -Since the return value of various APIs is Stream, it cannot be used without knowing it. -I want to run parallel processing using parallel (). (Added on 2017/06/01) -Create a different list using the contents of the list. (Added on 2017/06/02)

How to use Stream?

Example 1: Loop the list and pass it to the method

List<String> list = Arrays.asList("Part 1", "Part 2", "Part 3", "Part 4", "Part 5");
//Passing the string in the list to the fuga method of the Hoge class
list.stream().forEach(Hoge::fuga);

Example 2: Create an integer list from a string list

List<String> sl= Arrays.asList("11", "12", "13", "14", "15");
List<Integer> il = sl.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList());

Example 3: After getting all the csv paths under "C: \ temp", get the number of files starting with "A"

Path target = Paths.get("C:\temp");
try(
    Stream<Path> paths = Files.find(target , Integer.MAX_VALUE, (p, a) -> p.getFileName().endsWith(".csv"));
){
    //Try counting only CSV that starts with "A"
    long c = paths.filter(p -> p.getFileName().startsWith("A")).count();
}

The "->" that appears here and there is a "lambda expression", isn't it?

The streamAPI usually has a Consumer argument that allows you to pass method references and lambda expressions.

Well, when "->" appears, the left side is the argument, and the right side is the content of the method.

The method reference is written like "Hoge :: fuga". If you just read it, you can think that the parentheses of "Hoge.fuga (str)" are omitted.

Try to compare

Let's write how much the source shrinks by using Stream.

■ When using Stream

paths.filter(p -> p.getFileName().startsWith("A"))

■ When not using Stream

/**Filter part*/
private List<Path> filter(List<Path> paths) {
    List result = new ArrayList<>();
    for (Path p : paths) {
        if (isStartA(p)) {
            result.add(p);
        }
    }
    return result;
}
/**Lambda type part*/
private boolean isStartA(Path p) {
    return p.getFileName().startsWith("A");
}

You can see how the description is reduced by using Stream and lambda expressions!

Summary

Looking at the above results, it seems that it is better to use Stream or lambda expression more bang bang, When it comes to actually using it at work, if you do not say "for / while prohibited", the source will be messed up. It's a source that doesn't make sense to those who don't know. (People who don't understand this feel bad)

Since it has been updated conveniently, I would like to update humans as well!

Recommended Posts

Do you use Stream in Java?
Use Redis Stream in Java
[Java] Do not use "+" in append!
Use OpenCV in Java
Use PreparedStatement in Java
Java Stream API in 5 minutes
Do Scala Option.or Null in Java
Do HelloWorld in Java / IntelliJ / Gradle
Let's use Twilio in Java! (Introduction)
Things you often use when doing web development in Java
Use composite keys in Java Map.
Can you do it? Java EE
How to use classes in Java?
In Java 10, when you do gradle eclipse and JavaSE-1.10 comes out, ...
Multilingual Locale in Java How to use Locale
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
Do not use instance variables in partial
Try using the Stream API in Java
How to do base conversion in Java
[Java] Use cryptography in the standard library
Use "Rhino" which runs JavaScript in Java
Do TensorFlow in Java. It's easy, though. .. .. ..
Do not declare variables in List in Java
How do you write in Scala that was written in Java? (List → Map)
[JAVA] Stream type
Partization in Java
Try Java 8 Stream
Changes in Java 11
Rock-paper-scissors in Java
Java Stream API
Studying Java 8 (Stream)
[Java] Use Collectors.collectingAndThen
To you who were told "Don't use Stream API" in the field
Pi in Java
Java Stream termination
[Java] Stream processing
FizzBuzz in Java
Java 9 Optional :: stream
Be careful if you find SHIFT-JIS in Java
Do you need a memory-aware implementation of Java?
Use OpenCV_Contrib (ArUco) in Java! (Part 1-Build) (OpenCV-3.4.4)
With Tomcat you can use placeholders ($ {...}) in web.xml
[Java] Use of final in local variable declaration
[JAVA] [Spring] [MyBatis] Use IN () with SQL Builder
What to do when you think you can't do Groovy-> Java in IntelliJ IDEA CE
[Java] Why do you bother to use the interface (Spring is also available)
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Sample code to convert List to List <String> in Java Stream
Put java8 in centos7
[Java] Stream Collectors notes
I want to do something like "cls" in Java
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Use java.time in Jackson
Comments in Java source