|
| 1 | +package com.baeldung.collection.filtering; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Set; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +import org.hamcrest.Matchers; |
| 10 | +import org.junit.Assert; |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +/** |
| 14 | + * Various filtering examples. |
| 15 | + * |
| 16 | + * @author Rodolfo Felipe |
| 17 | + */ |
| 18 | +public class CollectionFilteringUnitTest { |
| 19 | + |
| 20 | + private List<Employee> buildEmployeeList() { |
| 21 | + return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); |
| 22 | + } |
| 23 | + |
| 24 | + private List<String> employeeNameFilter() { |
| 25 | + return Arrays.asList("Alice", "Mike", "Bob"); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() { |
| 30 | + List<Employee> filteredList = new ArrayList<>(); |
| 31 | + List<Employee> originalList = buildEmployeeList(); |
| 32 | + List<String> nameFilter = employeeNameFilter(); |
| 33 | + |
| 34 | + for (Employee employee : originalList) { |
| 35 | + for (String name : nameFilter) { |
| 36 | + if (employee.getName() |
| 37 | + .equalsIgnoreCase(name)) { |
| 38 | + filteredList.add(employee); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() { |
| 48 | + List<Employee> filteredList; |
| 49 | + List<Employee> originalList = buildEmployeeList(); |
| 50 | + List<String> nameFilter = employeeNameFilter(); |
| 51 | + |
| 52 | + filteredList = originalList.stream() |
| 53 | + .filter(employee -> nameFilter.contains(employee.getName())) |
| 54 | + .collect(Collectors.toList()); |
| 55 | + |
| 56 | + Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); |
| 57 | + } |
| 58 | + |
| 59 | + @Test |
| 60 | + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() { |
| 61 | + List<Employee> filteredList; |
| 62 | + List<Employee> originalList = buildEmployeeList(); |
| 63 | + Set<String> nameFilterSet = employeeNameFilter().stream() |
| 64 | + .collect(Collectors.toSet()); |
| 65 | + |
| 66 | + filteredList = originalList.stream() |
| 67 | + .filter(employee -> nameFilterSet.contains(employee.getName())) |
| 68 | + .collect(Collectors.toList()); |
| 69 | + |
| 70 | + Assert.assertThat(filteredList.size(), Matchers.is(nameFilterSet.size())); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments