10 Top Java Stream Tips That Simplify Your Code a Lot!

This is a community that may be useful to you

For one-on-one communication/interview brochure/resume optimization/job search questions, welcome to join the “Yudao Rapid Development Platform” Knowledge Planet. The following is some information provided by Planet:

  • “Project Practice (Video)”: Learn from books, “practice” from past events

  • “Internet High Frequency Interview Questions”: Studying with your resume, spring blossoms

  • “Architecture x System Design”: Overcoming difficulties and mastering high-frequency interview scenario questions

  • “Advancing Java Learning Guide”: systematic learning, the mainstream technology stack of the Internet

  • “Must-read Java Source Code Column”: Know what it is and why it is so

c8845fa406a0551769188ec3a94879b2.gif

This is an open source project that may be useful to you

Domestic Star is a 100,000+ open source project. The front-end includes management backend + WeChat applet, and the back-end supports monomer and microservice architecture.

Functions cover RBAC permissions, SaaS multi-tenancy, data permissions, mall, payment, workflow, large-screen reports, WeChat public account, etc.:

  • Boot address: https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • Cloud address: https://gitee.com/zhijiantianya/yudao-cloud

  • Video tutorial: https://doc.iocoder.cn

Source: medium.com/javarevisited/
10-java-stream-tips-must-read-
2063a84af3be

  • 1. Use raw streams for better performance

  • 2. Avoid nested flows

  • 3. Use parallel streams with caution

  • 4. Use lazy evaluation for better performance

  • 5. Avoid side effects

  • 6. Using streams with immutable objects

  • 7. Use filter() before map() to avoid unnecessary processing

  • 8. Prefer method references over lambda expressions

  • 9. Remove duplicates using distinct()

  • 10. Use sorted() with caution

30942c3be0cfdb7085c0f1e62d445f7a.jpeg

The Java Stream API is like a Swiss Army Knife for Java developers – it’s versatile, compact, and can handle a variety of tasks with ease.

It provides developers with a functional and declarative way to express complex data transformations and operations, making code more concise and expressive.

But with great power comes great responsibility, and using the Stream API effectively requires a deep understanding of best practices and common pitfalls.

Today we’ll explore some best practices for using the Java Stream API and show how to unleash the full potential of this amazing tool.

1. Use raw streams for better performance

When working with primitive types such as int, long, and double, use primitive streams such as IntStream, LongStream, and DoubleStream instead of boxed type streams such as Integer, Long, and Double. Raw streams can provide better performance by avoiding the cost of boxing and unboxing.

var array = new int[]{1, 2, 3, 4, 5};
var sum = Arrays.stream(array)
               .sum();

Backend management system + user applet implemented based on Spring Boot + MyBatis Plus + Vue & Element, supporting RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions

  • Project address: https://github.com/YunaiV/ruoyi-vue-pro

  • Video tutorial: https://doc.iocoder.cn/video/

2. Avoid nested flows

Best practice is to avoid nested flows as it can make code difficult to read and understand. Instead, try breaking the problem into smaller parts and using intermediate collections or local variables to store intermediate results.

var list1 = Arrays.asList("apple", "banana", "cherry");
var list2 = Arrays.asList("orange", "pineapple", "mango");
var result = Stream.concat(list1.stream(), list2.stream())
                  .filter(s -> s.length() > 5)
                  .collect(Collectors.toList());

Backend management system + user applet implemented based on Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element, supporting RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions

  • Project address: https://github.com/YunaiV/yudao-cloud

  • Video tutorial: https://doc.iocoder.cn/video/

3. Use parallel streams with caution

Parallel streams can provide better performance when processing large amounts of data, but they also introduce overhead and race conditions. Use parallel streams with caution and consider factors such as data size, operation complexity, and number of available processors.

var list = Arrays.asList(1, 2, 3, 4, 5);
var sum = list.parallelStream().reduce(0, Integer::sum);

4. Use lazy evaluation for better performance

The Stream API supports lazy evaluation, which means that no intermediate operations are performed before the terminal operation is called. As a best practice, try to use lazy evaluation to improve performance by reducing unnecessary calculations.

var list = Arrays.asList(1, 2, 3, 4, 5);
var result = list.stream()
                 .filter(n -> n > 3)
                 .findFirst();

5. Avoid side effects

The Stream API is designed to perform functional operations on data. Avoid introducing side effects, such as modifying variables outside the stream or performing I/O operations, as this may cause unpredictable behavior and reduce code readability.

var list = Arrays.asList("apple", "banana", "cherry");
var count = 0;
list.stream()
    .filter(s -> s.startsWith("a"))
    .forEach(s -> count + + );

6. Using streams with immutable objects

The Stream API works best with immutable objects. Using immutable objects ensures that the state of the stream is not modified during processing, which can lead to more predictable behavior and better code readability

var list = Arrays.asList("apple", "banana", "cherry");
var result = list.stream()
                 .map(String::toUpperCase)
                 .collect(Collectors.toList());

7. Use filter() before map() to avoid unnecessary processing

If your stream is likely to contain a large number of elements that don’t meet your criteria, use filter() before map() to avoid unnecessary processing. This can improve the performance of your code.

var list = Arrays.asList(1, 2, 3, 4, 5);
var filteredList = list.stream()
                       .filter(i -> i % 2 == 0)
                       .map(i -> i * 2)
                       .collect(Collectors.toList());

8. Prefer method references over lambda expressions

Method references can make our code more concise and readable compared to using lambda expressions. Where appropriate, use method references in preference to lambda expressions.

var list = Arrays.asList(1, 2, 3, 4, 5);
var sum = list.stream()
              .reduce(0, Integer::sum);

9. Use distinct() to remove duplicates

If your stream may contain duplicate elements, use the distinct() operation to remove them

var list = Arrays.asList(1, 2, 3, 3, 4, 5, 5);
var distinctList = list.stream()
                       .distinct()
                       .collect(Collectors.toList());

10. Use sorted() with caution

Sorted() operations can be expensive, especially for large streams. Use caution only when necessary. If you are sure that the input data is already sorted, you can skip this operation.

var list = Arrays.asList( 3 , 2 , 1 );
var SortedList = list.stream()
                     .sorted()
                     .collect(Collectors.toList());

In summary, the Java Stream API is a powerful and flexible tool that can significantly simplify the coding of data processing tasks.

By following the tips discussed in this article, you can ensure that your code is both efficient and effective. However, it is important to remember that effective use of the Java Stream API requires a full understanding of its capabilities and limitations.

Keep learning and exploring the world of Java Stream API to unlock its full potential.

Welcome to join my knowledge planet and comprehensively improve your technical capabilities.

To join, Long press” or “Scan” the QR code below:

eb6cb618b1560118b06af99d51958d84.png

Planet’s content includes: project practice, interviews and recruitment, source code analysis, and learning routes.

73275ed4037296b02502fad6ba29d7fb.png

976bc09c9f0fa81f6dee036fac864435.png2f274fe841b5db9f1c9bbe56a695d166.png 328e86dc9d2a15d794cf183d46744acd.pngeba95dbefb1394e9ed6 97437270fd2a4.png

If the article is helpful, please read it and forward it.
Thank you for your support (*^__^*)