Fix Format

This commit is contained in:
matt.rossi
2019-10-11 18:11:03 +02:00
parent db85c8f275
commit 1076a9c8d9
20374 changed files with 1638947 additions and 0 deletions
@@ -0,0 +1,47 @@
package com.baeldung.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class InfiniteStreamUnitTest {
@Test
public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() {
//given
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
//when
List<Integer> collect = infiniteStream
.limit(10)
.collect(Collectors.toList());
//then
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
}
@Test
public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() {
//given
Supplier<UUID> randomUUIDSupplier = UUID::randomUUID;
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
//when
List<UUID> randomInts = infiniteStreamOfRandomUUID
.skip(10)
.limit(10)
.collect(Collectors.toList());
//then
assertEquals(randomInts.size(), 10);
}
}
@@ -0,0 +1,118 @@
package com.baeldung.stream;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.StringWriter;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PeekUnitTest {
private StringWriter out;
@BeforeEach
void setup() {
out = new StringWriter();
}
@Test
void givenStringStream_whenCallingPeekOnly_thenNoElementProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append);
// then
assertThat(out.toString()).isEmpty();
}
@Test
void givenStringStream_whenCallingForEachOnly_thenElementsProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.forEach(out::append);
// then
assertThat(out.toString()).isEqualTo("AliceBobChuck");
}
@Test
void givenStringStream_whenCallingPeekAndNoopForEach_thenElementsProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append)
.forEach(this::noop);
// then
assertThat(out.toString()).isEqualTo("AliceBobChuck");
}
@Test
void givenStringStream_whenCallingPeekAndCollect_thenElementsProcessed() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append)
.collect(Collectors.toList());
// then
assertThat(out.toString()).isEqualTo("AliceBobChuck");
}
@Test
void givenStringStream_whenCallingPeekAndForEach_thenElementsProcessedTwice() {
// given
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
// when
nameStream.peek(out::append)
.forEach(out::append);
// then
assertThat(out.toString()).isEqualTo("AliceAliceBobBobChuckChuck");
}
@Test
void givenStringStream_whenCallingPeek_thenElementsProcessedTwice() {
// given
Stream<User> userStream = Stream.of(new User("Alice"), new User("Bob"), new User("Chuck"));
// when
userStream.peek(u -> u.setName(u.getName().toLowerCase()))
.map(User::getName)
.forEach(out::append);
// then
assertThat(out.toString()).isEqualTo("alicebobchuck");
}
private static class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private void noop(String s) {
}
}
@@ -0,0 +1,93 @@
package com.baeldung.stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
public class PrimitiveStreamsUnitTest {
private PrimitiveStreams streams = new PrimitiveStreams();
@Test
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
int[] integers = new int[] { 20, 98, 12, 7, 35 };
int min = streams.min(integers); // returns 7
assertEquals(7, min);
}
@Test
public void givenAnArrayOfIntegersWhenMaxIsCalledThenCorrectMaxIsReturned() {
int max = streams.max(20, 98, 12, 7, 35);
assertEquals(98, max);
}
@Test
public void givenAnArrayOfIntegersWhenSumIsCalledThenCorrectSumIsReturned() {
int sum = streams.sum(20, 98, 12, 7, 35);
assertEquals(172, sum);
}
@Test
public void givenAnArrayOfIntegersWhenAvgIsCalledThenCorrectAvgIsReturned() {
double avg = streams.avg(20, 98, 12, 7, 35);
assertTrue(34.4 == avg);
}
@Test
public void givenARangeOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
int sum = IntStream.range(1, 10).sum();
assertEquals(45, sum);
}
@Test
public void givenARangeClosedOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
int sum = IntStream.rangeClosed(1, 10).sum();
assertEquals(55, sum);
}
@Test
public void givenARangeWhenForEachIsCalledThenTheIndicesWillBePrinted() {
IntStream.rangeClosed(1, 5).parallel().forEach(System.out::println);
}
@Test
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
int sum = Stream.of(33, 45).mapToInt(i -> i).sum();
assertEquals(78, sum);
}
@Test
public void givenAnIntStreamThenGetTheEvenIntegers() {
List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
assertEquals(expected, evenInts);
}
class Person {
private int age;
Person(int age) {
this.age = age;
}
int getAge() {
return age;
}
}
}
@@ -0,0 +1,48 @@
package com.baeldung.stream;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class StreamAddUnitTest {
@Test
public void givenStream_whenAppendingObject_thenAppended() {
Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");
Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));
List<String> resultList = newStream.collect(Collectors.toList());
assertEquals(resultList.get(resultList.size() - 1), "A");
}
@Test
public void givenStream_whenPrependingObject_thenPrepended() {
Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
assertEquals(newStream.findFirst()
.get(), (Integer) 99);
}
@Test
public void givenStream_whenInsertingObject_thenInserted() {
Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);
Stream<Double> newStream = insertInStream(anStream, 9.9, 3);
List<Double> resultList = newStream.collect(Collectors.toList());
assertEquals(resultList.get(3), (Double) 9.9);
}
private <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
List<T> result = stream.collect(Collectors.toList());
result.add(index, elem);
return result.stream();
}
}
@@ -0,0 +1,42 @@
package com.baeldung.stream;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class StreamApiUnitTest {
@Test
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
List<String> valueList = new ArrayList<>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
String last = StreamApi.getLastElementUsingReduce(valueList);
assertEquals("Sean", last);
}
@Test
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
int last = StreamApi.getInfiniteStreamLastElementUsingReduce();
assertEquals(19, last);
}
@Test
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
List<String> valueList = new ArrayList<>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
String last = StreamApi.getLastElementUsingSkip(valueList);
assertEquals("Sean", last);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.stream;
import com.codepoetics.protonpack.Indexed;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class StreamIndicesUnitTest {
@Test
public void whenCalled_thenReturnListOfEvenIndexedStrings() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void whenCalled_thenReturnListOfEvenIndexedStringsVersionTwo() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void whenCalled_thenReturnListOfOddStrings() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
List<String> actualResult = StreamIndices.getOddIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void givenList_whenCalled_thenReturnListOfEvenIndexedStrings() {
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
List<Indexed<String>> expectedResult = Arrays
.asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed
.index(4, "Durim"));
List<Indexed<String>> actualResult = StreamIndices.getEvenIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void givenList_whenCalled_thenReturnListOfOddIndexedStrings() {
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
List<Indexed<String>> expectedResult = Arrays
.asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed
.index(5, "Shpetim"));
List<Indexed<String>> actualResult = StreamIndices.getOddIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void whenCalled_thenReturnListOfOddStringsVersionTwo() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
List<String> actualResult = StreamIndices.getOddIndexedStringsVersionTwo(names);
assertEquals(expectedResult, actualResult);
}
}
@@ -0,0 +1,83 @@
package com.baeldung.stream;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class StreamMapUnitTest {
private Map<String, String> books;
@Before
public void setup() {
books = new HashMap<>();
books.put("978-0201633610", "Design patterns : elements of reusable object-oriented software");
books.put("978-1617291999", "Java 8 in Action: Lambdas, Streams, and functional-style programming");
books.put("978-0134685991", "Effective Java");
}
@Test
public void whenOptionalVersionCalledForExistingTitle_thenReturnOptionalWithISBN() {
Optional<String> optionalIsbn = books.entrySet().stream()
.filter(e -> "Effective Java".equals(e.getValue()))
.map(Map.Entry::getKey).findFirst();
assertEquals("978-0134685991", optionalIsbn.get());
}
@Test
public void whenOptionalVersionCalledForNonExistingTitle_thenReturnEmptyOptionalForISBN() {
Optional<String> optionalIsbn = books.entrySet().stream()
.filter(e -> "Non Existent Title".equals(e.getValue()))
.map(Map.Entry::getKey).findFirst();
assertEquals(false, optionalIsbn.isPresent());
}
@Test
public void whenMultipleResultsVersionCalledForExistingTitle_aCollectionWithMultipleValuesIsReturned() {
books.put("978-0321356680", "Effective Java: Second Edition");
List<String> isbnCodes = books.entrySet().stream()
.filter(e -> e.getValue().startsWith("Effective Java"))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
assertTrue(isbnCodes.contains("978-0321356680"));
assertTrue(isbnCodes.contains("978-0134685991"));
}
@Test
public void whenMultipleResultsVersionCalledForNonExistingTitle_aCollectionWithNoValuesIsReturned() {
List<String> isbnCodes = books.entrySet().stream()
.filter(e -> e.getValue().startsWith("Spring"))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
assertTrue(isbnCodes.isEmpty());
}
@Test
public void whenKeysFollowingPatternReturnsAllValuesForThoseKeys() {
List<String> titlesForKeyPattern = books.entrySet().stream()
.filter(e -> e.getKey().startsWith("978-0"))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
assertEquals(2, titlesForKeyPattern.size());
assertTrue(titlesForKeyPattern.contains("Design patterns : elements of reusable object-oriented software"));
assertTrue(titlesForKeyPattern.contains("Effective Java"));
}
}
@@ -0,0 +1,80 @@
package com.baeldung.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamOperateAndRemoveUnitTest {
private List<Item> itemList;
@Before
public void setup() {
itemList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
itemList.add(new Item(i));
}
}
@Test
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
.collect(Collectors.toList());
Assert.assertEquals(5, filteredList.size());
}
@Test
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
final Predicate<Item> isQualified = item -> item.isQualified();
itemList.stream().filter(isQualified).forEach(item -> item.operate());
itemList.removeIf(isQualified);
Assert.assertEquals(5, itemList.size());
}
@Test
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
final List<Item> operatedList = new ArrayList<>();
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
item.operate();
operatedList.add(item);
});
itemList.removeAll(operatedList);
Assert.assertEquals(5, itemList.size());
}
class Item {
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private final int value;
public Item(final int value) {
this.value = value;
}
public boolean isQualified() {
return value % 2 == 0;
}
public void operate() {
logger.info("Even Number: " + this.value);
}
}
}
@@ -0,0 +1,65 @@
package com.baeldung.stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.Test;
import com.baeldung.stream.mycollectors.MyImmutableListCollector;
import com.google.common.collect.ImmutableList;
public class StreamToImmutableUnitTest {
@Test
public void whenUsingCollectingToImmutableSet_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c");
List<String> result = givenList.stream()
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
System.out.println(result.getClass());
}
@Test
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> result = givenList.stream()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
System.out.println(result.getClass());
}
@Test
public void whenCollectToImmutableList_thenSuccess() {
List<Integer> list = IntStream.range(0, 9)
.boxed()
.collect(ImmutableList.toImmutableList());
System.out.println(list.getClass());
}
@Test
public void whenCollectToMyImmutableListCollector_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
.collect(MyImmutableListCollector.toImmutableList());
System.out.println(result.getClass());
}
@Test
public void whenPassingSupplier_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
System.out.println(result.getClass());
}
}
@@ -0,0 +1,35 @@
package com.baeldung.stream;
import static org.junit.Assert.fail;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.Test;
public class SupplierStreamUnitTest {
@Test(expected = IllegalStateException.class)
public void givenStream_whenStreamUsedTwice_thenThrowException() {
Stream<String> stringStream = Stream.of("A", "B", "C", "D");
Optional<String> result1 = stringStream.findAny();
System.out.println(result1.get());
Optional<String> result2 = stringStream.findFirst();
System.out.println(result2.get());
}
@Test
public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() {
try {
Supplier<Stream<String>> streamSupplier = () -> Stream.of("A", "B", "C", "D");
Optional<String> result1 = streamSupplier.get().findAny();
System.out.println(result1.get());
Optional<String> result2 = streamSupplier.get().findFirst();
System.out.println(result2.get());
} catch (IllegalStateException e) {
fail();
}
}
}
@@ -0,0 +1,72 @@
package com.baeldung.stream.filter;
import org.junit.Test;
import org.junit.Before;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class StreamCountUnitTest {
private List<Customer> customers;
@Before
public void setUp() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
customers = Arrays.asList(john, sarah, charles, mary);
}
@Test
public void givenListOfCustomers_whenCount_thenGetListSize() {
long count = customers
.stream()
.count();
assertThat(count).isEqualTo(4L);
}
@Test
public void givenListOfCustomers_whenFilterByPointsOver100AndCount_thenGetTwo() {
long countBigCustomers = customers
.stream()
.filter(c -> c.getPoints() > 100)
.count();
assertThat(countBigCustomers).isEqualTo(2L);
}
@Test
public void givenListOfCustomers_whenFilterByPointsAndNameAndCount_thenGetOne() {
long count = customers
.stream()
.filter(c -> c.getPoints() > 10 && c.getName().startsWith("Charles"))
.count();
assertThat(count).isEqualTo(1L);
}
@Test
public void givenListOfCustomers_whenNoneMatchesFilterAndCount_thenGetZero() {
long count = customers
.stream()
.filter(c -> c.getPoints() > 500)
.count();
assertThat(count).isEqualTo(0L);
}
@Test
public void givenListOfCustomers_whenUsingMethodOverHundredPointsAndCount_thenGetTwo() {
long count = customers
.stream()
.filter(Customer::hasOverHundredPoints)
.count();
assertThat(count).isEqualTo(2L);
}
}
@@ -0,0 +1,160 @@
package com.baeldung.stream.filter;
import org.junit.jupiter.api.Test;
import pl.touk.throwing.ThrowingPredicate;
import pl.touk.throwing.exception.WrappedException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
public class StreamFilterUnitTest {
@Test
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
}
@Test
public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> charlesWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100 && c
.getName()
.startsWith("Charles"))
.collect(Collectors.toList());
assertThat(charlesWithMoreThan100Points).hasSize(1);
assertThat(charlesWithMoreThan100Points).contains(charles);
}
@Test
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(Customer::hasOverHundredPoints)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
}
@Test
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
List<Optional<Customer>> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty());
List<Customer> customersWithMoreThan100Points = customers
.stream()
.flatMap(c -> c
.map(Stream::of)
.orElseGet(Stream::empty))
.filter(Customer::hasOverHundredPoints)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get());
}
@Test
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
assertThatThrownBy(() -> customers
.stream()
.filter(Customer::hasValidProfilePhotoWithoutCheckedException)
.count()).isInstanceOf(RuntimeException.class);
}
@Test
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
assertThatThrownBy(() -> customers
.stream()
.filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto)))
.collect(Collectors.toList())).isInstanceOf(WrappedException.class);
}
@Test
public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithValidProfilePhoto = customers
.stream()
.filter(c -> {
try {
return c.hasValidProfilePhoto();
} catch (IOException e) {
//handle exception
}
return false;
})
.collect(Collectors.toList());
assertThat(customersWithValidProfilePhoto).hasSize(2);
assertThat(customersWithValidProfilePhoto).contains(john, mary);
}
@Test
public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() {
List<Customer> customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150),
new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"));
assertThatThrownBy(() -> customers
.stream()
.filter(c -> {
try {
return c.hasValidProfilePhoto();
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.stream.mycollectors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class MyImmutableListCollector {
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
return Collector.of(supplier, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
return toImmutableList(ArrayList::new);
}
}
@@ -0,0 +1,136 @@
package com.baeldung.stream.sum;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class StreamSumUnitTest {
@Test
public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers);
assertEquals(15, sum.intValue());
}
@Test
public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers);
assertEquals(15, sum.intValue());
}
@Test
public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer sum = StreamSumCalculator.getSumUsingReduce(integers);
assertEquals(15, sum.intValue());
}
@Test
public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer sum = StreamSumCalculator.getSumUsingCollect(integers);
assertEquals(15, sum.intValue());
}
@Test
public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer sum = StreamSumCalculator.getSumUsingSum(integers);
assertEquals(15, sum.intValue());
}
@Test
public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() {
Item item1 = new Item(1, 10);
Item item2 = new Item(2, 15);
Item item3 = new Item(3, 25);
Item item4 = new Item(4, 40);
List<Item> items = Arrays.asList(item1, item2, item3, item4);
Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items);
assertEquals(90, sum.intValue());
}
@Test
public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() {
Item item1 = new Item(1, 10);
Item item2 = new Item(2, 15);
Item item3 = new Item(3, 25);
Item item4 = new Item(4, 40);
List<Item> items = Arrays.asList(item1, item2, item3, item4);
Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items);
assertEquals(90, sum.intValue());
}
@Test
public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() {
Item item1 = new Item(1, 10);
Item item2 = new Item(2, 15);
Item item3 = new Item(3, 25);
Item item4 = new Item(4, 40);
List<Item> items = Arrays.asList(item1, item2, item3, item4);
Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items);
assertEquals(90, sum.intValue());
}
@Test
public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() {
Item item1 = new Item(1, 10);
Item item2 = new Item(2, 15);
Item item3 = new Item(3, 25);
Item item4 = new Item(4, 40);
List<Item> items = Arrays.asList(item1, item2, item3, item4);
Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items);
assertEquals(90, sum.intValue());
}
@Test
public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() {
Item item1 = new Item(1, 10);
Item item2 = new Item(2, 15);
Item item3 = new Item(3, 25);
Item item4 = new Item(4, 40);
List<Item> items = Arrays.asList(item1, item2, item3, item4);
Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items);
assertEquals(90, sum.intValue());
}
@Test
public void givenMapWhenSummingThenCorrectValueReturned() {
Map<Object, Integer> map = new HashMap<Object, Integer>();
map.put(1, 10);
map.put(2, 15);
map.put(3, 25);
map.put(4, 40);
Integer sum = StreamSumCalculator.getSumOfMapValues(map);
assertEquals(90, sum.intValue());
}
@Test
public void givenStringWhenSummingThenCorrectValueReturned() {
String string = "Item1 10 Item2 25 Item3 30 Item4 45";
Integer sum = StreamSumCalculator.getSumIntegersFromString(string);
assertEquals(110, sum.intValue());
}
}