Junior — Middle
Kuidas rakendada tõhusat otsingut kogumisis olevate elementide leidmiseks, mis vastavad antud tingimusele?
sobes.tech AI
Vastus AI-lt
To efficiently search for elements in a collection that meet a given condition, in Java, you can use the Stream API, which allows filtering elements using lambda expressions.
Example: find all numbers greater than 10 in a list:
import java.util.*;
import java.util.stream.*;
List<Integer> numbers = Arrays.asList(5, 12, 3, 21, 8);
List<Integer> filtered = numbers.stream()
.filter(n -> n > 10)
.collect(Collectors.toList());
System.out.println(filtered); // [12, 21]
This approach is efficient and easy to read, especially for large collections. For more complex conditions, you can combine filters or use parallel streams to improve performance.