Here are some common use cases and examples of Java Streams:
1. Filtering Elements:
- Use
filterto select elements based on a condition.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList()); // Result: ["John", "Jane"]
2. Mapping Elements:
- Use
mapto transform elements.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
List<Integer> nameLengths = names.stream()
.map(String::length)
.collect(Collectors.toList()); // Result: [4, 4, 5, 3]
3. Sorting Elements:
- Use
sortedto sort elements.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());// Result: ["Alice", "Bob", "Jane", "John"]
4. Combining Operations:
- You can chain multiple operations together
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
List<String> result = names.stream()
.filter(name -> name.length() == 4)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());// Result: ["ALICE", "JANE", "JOHN"]
5. Finding Elements:
- Use
findFirstorfindAnyto get the first matching element.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
Optional<String> result = names.stream()
.filter(name -> name.startsWith("J"))
.findFirst(); // Result: "John" (or any name starting with "J")
6. Counting Elements:
- Use
countto count the number of elements.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
long count = names.stream()
.filter(name -> name.length() == 4)
.count();// Result: 3
7. Grouping and Collecting:
- Use
groupingByfor grouping elements.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob");
Map<Integer, List<String>> groupedByLength = names.stream()
.collect(Collectors.groupingBy(String::length)); // Result: {3=["Bob"], 4=["Jane", "John"], 5=["Alice"]}
8. Parallel Streams:
- Use
parallelStreamto process elements in parallel for improved performance.
List<String> names = Arrays.asList("John", "Jane", "Alice", "Bob"); long count = names.parallelStream()
.filter(name -> name.length() == 4)
.count(); // Result: 3 (processed in parallel)These are just a few examples to illustrate the use of Java Streams. The API provides a rich set of functions, and you can combine them in various ways to perform complex operations on your data. It's important to consider the characteristics of the data and the nature of the operations you are performing when deciding whether to use streams or traditional loops.
No comments:
Post a Comment