添加 Java 的 streams 处理模块
This commit is contained in:
+31
@@ -0,0 +1,31 @@
|
||||
package com.ossez.conversion;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
|
||||
public class IterableStreamConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIterable_whenConvertedToStream_thenNotNull() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToList_thenCorrect() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.ossez.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);
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.ossez.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);
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.ossez.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);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.ossez.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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.ossez.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);
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package com.ossez.stream.filter;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
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());
|
||||
|
||||
Assertions.assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
Assertions.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());
|
||||
|
||||
Assertions.assertThat(charlesWithMoreThan100Points).hasSize(1);
|
||||
Assertions.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());
|
||||
|
||||
Assertions.assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
Assertions.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());
|
||||
|
||||
Assertions.assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
Assertions.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());
|
||||
|
||||
Assertions.assertThat(customersWithValidProfilePhoto).hasSize(2);
|
||||
Assertions.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);
|
||||
}
|
||||
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package com.ossez.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());
|
||||
}
|
||||
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.ossez.streamordering;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
import org.openjdk.jmh.runner.options.TimeValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class BenchmarkManualTest
|
||||
{
|
||||
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
// Specify which benchmarks to run.
|
||||
// You can be more specific if you'd like to run only one benchmark per test.
|
||||
.include(this.getClass().getName() + ".*")
|
||||
// Set the following options as needed
|
||||
.mode (Mode.AverageTime)
|
||||
.timeUnit(TimeUnit.MICROSECONDS)
|
||||
.warmupTime(TimeValue.seconds(1))
|
||||
.warmupIterations(2)
|
||||
.measurementTime(TimeValue.seconds(1))
|
||||
.measurementIterations(2)
|
||||
.threads(2)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
|
||||
//.addProfiler(WinPerfAsmProfiler.class)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
|
||||
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
|
||||
//section 5.1.
|
||||
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
|
||||
// The JMH samples are the best documentation for how to use it
|
||||
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState
|
||||
{
|
||||
List<Integer> list;
|
||||
|
||||
@Setup(Level.Trial) public void
|
||||
initialize() {
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
list = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
list.add (rand.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark public void
|
||||
benchmark1 (BenchmarkState state, Blackhole bh) {
|
||||
|
||||
List<Integer> list = state.list;
|
||||
|
||||
for (int i = 0; i < 1000; i++)
|
||||
bh.consume (list.get (i));
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package com.ossez.streamordering;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamsOrderingUnitTest {
|
||||
|
||||
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.setLevel(Level.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] setOutput = set.stream().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().parallel().toArray();
|
||||
Object[] setOutput = set.stream().parallel().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
|
||||
Set<Integer> set = new TreeSet<>(
|
||||
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
|
||||
|
||||
Object[] orderedArray = set.stream()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
Object[] unorderedArray = set.stream()
|
||||
.unordered()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
|
||||
logger.info(Arrays.toString(orderedArray));
|
||||
logger.info(Arrays.toString(unorderedArray));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
|
||||
|
||||
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] listOutputSorted = list.stream().sorted().toArray();
|
||||
|
||||
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
|
||||
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
|
||||
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
|
||||
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
|
||||
|
||||
assertEquals("[B, A, C, D, F]", collectionList.toString());
|
||||
assertEquals("[A, B, C, D, F]", collectionSet.toString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC");
|
||||
|
||||
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
|
||||
|
||||
Object[] keySet = hashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
|
||||
|
||||
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(u, v) -> u,
|
||||
LinkedHashMap::new
|
||||
));
|
||||
|
||||
Object[] keySet = linkedHashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user