|
| 1 | +package com.baeldung.removal; |
| 2 | + |
| 3 | +import org.junit.Before; |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +import static org.hamcrest.Matchers.is; |
| 10 | +import static org.junit.Assert.assertThat; |
| 11 | + |
| 12 | +public class RemovalUnitTest { |
| 13 | + |
| 14 | + Collection<String> names; |
| 15 | + Collection<String> expected; |
| 16 | + Collection<String> removed; |
| 17 | + |
| 18 | + @Before |
| 19 | + public void setupTestData() { |
| 20 | + names = new ArrayList<>(); |
| 21 | + expected = new ArrayList<>(); |
| 22 | + removed = new ArrayList<>(); |
| 23 | + |
| 24 | + names.add("John"); |
| 25 | + names.add("Ana"); |
| 26 | + names.add("Mary"); |
| 27 | + names.add("Anthony"); |
| 28 | + names.add("Mark"); |
| 29 | + |
| 30 | + expected.add("John"); |
| 31 | + expected.add("Mary"); |
| 32 | + expected.add("Mark"); |
| 33 | + |
| 34 | + removed.add("Ana"); |
| 35 | + removed.add("Anthony"); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { |
| 40 | + Iterator<String> i = names.iterator(); |
| 41 | + |
| 42 | + while (i.hasNext()) { |
| 43 | + String e = i.next(); |
| 44 | + if (e.startsWith("A")) { |
| 45 | + i.remove(); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + assertThat(names, is(expected)); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { |
| 54 | + names.removeIf(e -> e.startsWith("A")); |
| 55 | + assertThat(names, is(expected)); |
| 56 | + } |
| 57 | + |
| 58 | + @Test |
| 59 | + public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { |
| 60 | + Collection<String> filteredCollection = names |
| 61 | + .stream() |
| 62 | + .filter(e -> !e.startsWith("A")) |
| 63 | + .collect(Collectors.toList()); |
| 64 | + assertThat(filteredCollection, is(expected)); |
| 65 | + } |
| 66 | + |
| 67 | + @Test |
| 68 | + public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() { |
| 69 | + Map<Boolean, List<String>> classifiedElements = names |
| 70 | + .stream() |
| 71 | + .collect(Collectors.partitioningBy((String e) -> !e.startsWith("A"))); |
| 72 | + |
| 73 | + assertThat(classifiedElements.get(Boolean.TRUE), is(expected)); |
| 74 | + assertThat(classifiedElements.get(Boolean.FALSE), is(removed)); |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments