Interview Questions
Java
java Advanced Interview questions
Java Certification
Java Concurrent Tutorials
Java interview questions
Java Interview Questions
Java Interview Questions
Java8 Examples
Java8 Streams Examples
Java 8 introduced the Stream API, which allows you to perform functional-style operations on collections of data. Here are some examples of using the Stream API:
1. Filtering a list of integers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
2. Mapping a list of strings to a list of their lengths:
List<String> words = Arrays.asList("foo", "bar", "baz", "qux");
List<Integer> wordLengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
3. Summing a list of numbers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
4. Finding the maximum value in a list of numbers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> max = numbers.stream()
.max(Integer::compareTo);
5. Counting the number of elements in a list that match a certain condition:
List<String> words = Arrays.asList("foo", "bar", "baz", "qux");
long count = words.stream()
.filter(s -> s.startsWith("b"))
.count();
6. Sorting a list of strings:
List<String> words = Arrays.asList("foo", "bar", "baz", "qux");
List<String> sortedWords = words.stream()
.sorted()
.collect(Collectors.toList());
7. Grouping a list of numbers by their remainder when divided by a certain value:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Integer, List<Integer>> groupedNumbers = numbers.stream()
.collect(Collectors.groupingBy(n -> n % 3));
8. Joining a list of strings into a single string:
List<String> words = Arrays.asList("foo", "bar", "baz", "qux");
String joinedWords = words.stream()
.collect(Collectors.joining(", "));
9. Finding the first element in a list that matches a certain condition:
List<String> words = Arrays.asList("foo", "bar", "baz", "qux");
Optional<String> firstWord = words.stream()
.filter(s -> s.length() > 3)
.findFirst();
10. Finding the first element in a list that matches a certain condition:
List<String> words = Arrays.asList("foo", "bar", "baz", "qux");
Optional<String> firstWord = words.stream()
.filter(s -> s.length() > 3)
.findFirst();
11. Finding the distinct elements in a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10);
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
12. Counting frequency of elements in a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10);
Map<Integer, Long> frequency = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));