|
| 1 | +package com.baeldung.streams.findanyvsanymatch; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | + |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +import static org.junit.jupiter.api.Assertions.*; |
| 9 | + |
| 10 | +public class FindAnyAnyMatchUnitTest { |
| 11 | + |
| 12 | + @Test |
| 13 | + public void whenFilterStreamUsingFindAny_thenOK() { |
| 14 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
| 15 | + |
| 16 | + Integer result = numbers.stream() |
| 17 | + .filter(n -> n % 2 == 0) |
| 18 | + .findAny() |
| 19 | + .orElse(null); |
| 20 | + |
| 21 | + assertNotNull(result); |
| 22 | + assertTrue(Arrays.asList(2, 4, 6, 8, 10).contains(result)); |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + public void whenParallelStreamUsingFindAny_thenOK() { |
| 27 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
| 28 | + |
| 29 | + Integer result = numbers.parallelStream() |
| 30 | + .filter(n -> n % 2 == 0) |
| 31 | + .findAny() |
| 32 | + .orElse(null); |
| 33 | + |
| 34 | + assertNotNull(result); |
| 35 | + assertTrue(Arrays.asList(2, 4, 6, 8, 10).contains(result)); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + @Test |
| 40 | + public void whenFilterStreamUsingAnyMatch_thenOK() { |
| 41 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
| 42 | + |
| 43 | + boolean result = numbers.parallelStream() |
| 44 | + .anyMatch(n -> n % 2 == 0); |
| 45 | + |
| 46 | + assertTrue(result); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void whenFilterStreamUsingFindFirst_thenOK() { |
| 51 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
| 52 | + |
| 53 | + Integer result = numbers.stream() |
| 54 | + .filter(n -> n % 2 == 0) |
| 55 | + .findFirst() |
| 56 | + .orElse(null); |
| 57 | + |
| 58 | + assertNotNull(result); |
| 59 | + assertEquals(2, result); |
| 60 | + } |
| 61 | + |
| 62 | + @Test |
| 63 | + public void whenCountingElementsInStream_thenOK() { |
| 64 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); |
| 65 | + |
| 66 | + long count = numbers.stream() |
| 67 | + .filter(n -> n % 2 == 0) |
| 68 | + .count(); |
| 69 | + |
| 70 | + assertEquals(5, count); |
| 71 | + } |
| 72 | + |
| 73 | + @Test |
| 74 | + public void whenCheckingAllMatch_thenOK() { |
| 75 | + List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10); |
| 76 | + |
| 77 | + boolean allEven = numbers.stream() |
| 78 | + .allMatch(n -> n % 2 == 0); |
| 79 | + |
| 80 | + assertTrue(allEven); |
| 81 | + } |
| 82 | + |
| 83 | +} |
0 commit comments