Junior — Middle
Can you list the main methods provided by the Stream API in Java?
sobes.tech AI
Answer from AI
The main methods of the Stream API in Java include:
filter(Predicate)— filters elements based on a condition.map(Function)— transforms elements.flatMap(Function)— transforms and "flattens" nested structures.sorted()andsorted(Comparator)— sort elements.distinct()— removes duplicates.limit(long)— limits the number of elements.skip(long)— skips the first N elements.forEach(Consumer)— performs an action for each element.collect(Collector)— collects elements into a collection or other result.reduce(BinaryOperator)— reduces elements to a single value.count()— returns the number of elements.anyMatch(Predicate),allMatch(Predicate),noneMatch(Predicate)— check conditions for elements.
Example usage:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");
List<String> filtered = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(filtered); // [ANNA]