Junior — Middle
Can you name the main intermediate operations used for data processing or in streams?
sobes.tech AI
Answer from AI
In Java, intermediate operations are used to process data in streams, which return a new stream and allow chaining transformations.
Main intermediate operations:
- map — transforms each element of the stream by applying a function.
- filter — filters elements based on a condition.
- flatMap — transforms each element into a stream and merges them into a single stream.
- distinct — removes duplicates.
- sorted — sorts the elements.
- limit — limits the number of elements.
- skip — skips a specified number of elements.
Example:
List<String> names = Arrays.asList("Anna", "Bob", "Alice", "Brian");
List<String> filtered = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
System.out.println(filtered); // [ALICE, ANNA]
Here, we filtered names starting with "A", converted them to uppercase, and sorted them.