| 13 | import java.util.stream.Stream; |
| 14 | |
| 15 | public class Filtering { |
| 16 | |
| 17 | @Test |
| 18 | public void filter() throws Exception { |
| 19 | List<Car> cars = MockData.getCars(); |
| 20 | |
| 21 | Predicate<Car> carPredicate = car -> car.getPrice() < 20_000.00; |
| 22 | Predicate<Car> yellow = car -> car.getColor().equals("Yellow"); |
| 23 | |
| 24 | List<Car> carsLessThan20k = cars.stream() |
| 25 | .filter(carPredicate) |
| 26 | .filter(yellow) |
| 27 | .collect(Collectors.toList()); |
| 28 | |
| 29 | carsLessThan20k.forEach(System.out::println); |
| 30 | } |
| 31 | |
| 32 | @Test |
| 33 | public void dropWhile() throws Exception { |
| 34 | System.out.println("using filter"); |
| 35 | Stream.of(2, 4, 6, 8, 9, 10, 12).filter(n -> n % 2 == 0) |
| 36 | .forEach(n -> System.out.print(n + " ")); |
| 37 | System.out.println(); |
| 38 | System.out.println("using dropWhile"); |
| 39 | Stream.of(2, 4, 6, 8, 9, 10, 12).dropWhile(n -> n % 2 == 0) |
| 40 | .forEach(n -> System.out.print(n + " ")); |
| 41 | |
| 42 | } |
| 43 | |
| 44 | @Test |
| 45 | public void takeWhile() throws Exception { |
| 46 | // using filter |
| 47 | System.out.println("using filter"); |
| 48 | Stream.of(2, 4, 6, 8, 9, 10, 12).filter(n -> n % 2 == 0) |
| 49 | .forEach(n -> System.out.print(n + " ")); |
| 50 | |
| 51 | System.out.println(); |
| 52 | System.out.println("using take while"); |
| 53 | Stream.of(2, 4, 6, 8, 9, 10, 12).takeWhile(n -> n % 2 == 0) |
| 54 | .forEach(n -> System.out.print(n + " ")); |
| 55 | } |
| 56 | |
| 57 | @Test |
| 58 | public void findFirst() throws Exception { |
| 59 | int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
| 60 | int result = Arrays.stream(numbers).filter(n -> n == 50) |
| 61 | .findFirst() |
| 62 | .orElse(-1); |
| 63 | System.out.println(result); |
| 64 | |
| 65 | } |
| 66 | |
| 67 | @Test |
| 68 | public void findAny() throws Exception { |
| 69 | int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10}; |
| 70 | int result = Arrays.stream(numbers).filter(n -> n == 9) |
| 71 | .findAny() |
| 72 | .orElse(-1); |
nothing calls this directly
no outgoing calls
no test coverage detected