Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions stream-api/src/test/java/stream/api/Exercise1Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

public class Exercise1Test extends ClassicOnlineStore {

private final static int BUDGET = 10000;

@Easy @Test
public void findRichCustomers() {
List<Customer> customerList = this.mall.getCustomerList();
Expand All @@ -27,8 +29,8 @@ public void findRichCustomers() {
* Create a {@link Stream} from customerList only including customer who has more budget than 10000.
* Use lambda expression for Predicate and {@link Stream#filter} for filtering.
*/
Predicate<Customer> richCustomerCondition = null;
Stream<Customer> richCustomerStream = null;
Predicate<Customer> richCustomerCondition = (c)-> c.getBudget() > BUDGET;
Stream<Customer> richCustomerStream = customerList.stream().filter(richCustomerCondition);

assertTrue("Solution for Predicate should be lambda expression", AssertUtil.isLambda(richCustomerCondition));
List<Customer> richCustomer = richCustomerStream.collect(Collectors.toList());
Expand All @@ -45,8 +47,8 @@ public void howOldAreTheCustomers() {
* Use method reference(best) or lambda expression(okay) for creating {@link Function} which will
* convert {@link Customer} to {@link Integer}, and then apply it by using {@link Stream#map}.
*/
Function<Customer, Integer> getAgeFunction = null;
Stream<Integer> ageStream = null;
Function<Customer, Integer> getAgeFunction = c ->{ return c.getAge();};
Stream<Integer> ageStream = customerList.stream().map(getAgeFunction);

assertTrue(AssertUtil.isLambda(getAgeFunction));
List<Integer> richCustomer = ageStream.collect(Collectors.toList());
Expand Down
38 changes: 31 additions & 7 deletions stream-api/src/test/java/stream/api/Exercise2Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import common.test.tool.entity.Customer;
import common.test.tool.entity.Item;
import common.test.tool.util.AssertUtil;
import java.util.Collections;

import org.junit.Test;

Expand All @@ -19,6 +20,9 @@

public class Exercise2Test extends ClassicOnlineStore {

private Function<Customer, Integer> getAgeFunction = c ->{return c.getAge();};
private Function<Customer, String> getNameFunction = c ->{return c.getName();};

@Easy @Test
public void sortByAge() {
List<Customer> customerList = this.mall.getCustomerList();
Expand All @@ -27,7 +31,16 @@ public void sortByAge() {
* Create a stream with ascending ordered age values.
* Use {@link Stream#sorted} to sort them.
*/
Stream<Integer> sortedAgeStream = null;
//Function<Customer, Integer> getAgeFunction = c ->{return c.getAge();};

Comparator<Customer> comparator = (Customer c1, Customer c2)-> {
return c1.getAge().compareTo(c2.getAge());
};

//Collections.sort(customerList);

Stream<Integer> sortedAgeStream = customerList.stream().sorted(comparator).map(getAgeFunction);


List<Integer> sortedAgeList = sortedAgeStream.collect(Collectors.toList());
assertThat(sortedAgeList, contains(21, 22, 22, 26, 27, 28, 32, 35, 36, 38));
Expand All @@ -40,8 +53,13 @@ public void descSortByAge() {
/**
* Create a stream with descending ordered age values.
*/
Comparator<Integer> descOrder = null;
Stream<Integer> sortedAgeStream = null;
//
//Function<Customer, Integer> getAgeFunction = c ->{return c.getAge();};

Comparator<Integer> descOrder = (Integer nb1, Integer nb2)->{
return - nb1.compareTo(nb2);
};
Stream<Integer> sortedAgeStream = customerList.stream().map(getAgeFunction).sorted(descOrder);

assertTrue(AssertUtil.isLambda(descOrder));
List<Integer> sortedAgeList = sortedAgeStream.collect(Collectors.toList());
Expand All @@ -55,7 +73,12 @@ public void top3RichCustomer() {
/**
* Create a stream with top 3 rich customers using {@link Stream#limit} to limit the size of the stream
*/
Stream<String> top3RichCustomerStream = null;

Comparator<Customer> comparator = (Customer c1, Customer c2)-> {
return -c1.getBudget().compareTo(c2.getBudget());
};

Stream<String> top3RichCustomerStream = customerList.stream().sorted(comparator).map(getNameFunction).limit(3);

List<String> top3RichCustomerList = top3RichCustomerStream.collect(Collectors.toList());
assertThat(top3RichCustomerList, contains("Diana", "Andrew", "Chris"));
Expand All @@ -68,7 +91,7 @@ public void distinctAge() {
/**
* Create a stream with distinct age values using {@link Stream#distinct}
*/
Stream<Integer> distinctAgeStream = null;
Stream<Integer> distinctAgeStream = customerList.stream().map(getAgeFunction).distinct();

List<Integer> distinctAgeList = distinctAgeStream.collect(Collectors.toList());
assertThat(distinctAgeList, contains(22, 27, 28, 38, 26, 32, 35, 21, 36));
Expand All @@ -82,8 +105,9 @@ public void itemsCustomersWantToBuy() {
* Create a stream with items' names stored in {@link Customer.wantToBuy}
* Use {@link Stream#flatMap} to create a stream from each element of a stream.
*/
Function<Customer, Stream<Item>> getItemStream = null;
Stream<String> itemStream = null;
Function<Customer, Stream<Item>> getItemStream = customer -> {return customer.getWantToBuy().stream();};
Function<Item, String> getNameItemFunction = item -> item.getName();
Stream<String> itemStream = customerList.stream().flatMap(getItemStream).map(getNameItemFunction);

assertTrue(AssertUtil.isLambda(getItemStream));
List<String> itemList = itemStream.collect(Collectors.toList());
Expand Down
18 changes: 13 additions & 5 deletions stream-api/src/test/java/stream/api/Exercise3Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import common.test.tool.dataset.ClassicOnlineStore;
import common.test.tool.entity.Customer;

import common.test.tool.entity.Item;
import org.junit.Test;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

import static org.hamcrest.Matchers.is;
Expand All @@ -23,7 +25,9 @@ public void howManyItemsWanted() {
/**
* Count how many items there are in {@link Customer.wantToBuy} using {@link Stream#count}
*/
long sum = 0L;
Function<Customer, Stream<Item>> getItemStream = customer -> { return customer.getWantToBuy().stream();};
Function<Item, String> getItemFunction = item -> { return item.getName();};
long sum = customerList.stream().flatMap(getItemStream).map(getItemFunction).count();

assertThat(sum, is(32L));
}
Expand All @@ -36,8 +40,11 @@ public void richestCustomer() {
* Find the richest customer's budget by using {@link Stream#max} and {@link Comparator#naturalOrder}
* Don't use {@link Stream#sorted}
*/
Comparator<Integer> comparator = null;
Optional<Integer> richestCustomer = null;

Function<Customer, Integer> getBudgetFunction = customer -> {return customer.getBudget();};
// Comparator<Integer> comparator = (nb1, nb2) -> {return nb1.compareTo(nb2);};
Comparator<Integer> comparator = Comparator.naturalOrder() ;
Optional<Integer> richestCustomer = customerList.stream().map(getBudgetFunction).max(comparator);

assertThat(comparator.getClass().getSimpleName(), is("NaturalOrderComparator"));
assertThat(richestCustomer.get(), is(12000));
Expand All @@ -51,8 +58,9 @@ public void youngestCustomer() {
* Find the youngest customer by using {@link Stream#min}
* Don't use {@link Stream#sorted}
*/
Comparator<Customer> comparator = null;
Optional<Customer> youngestCustomer = null;
//Function<Customer, Integer> getAgeFunction = customer -> {return customer.getAge();};
Comparator<Customer> comparator = (c1, c2) -> {return c1.getAge().compareTo(c2.getAge());};
Optional<Customer> youngestCustomer = customerList.stream().min(comparator);

assertThat(youngestCustomer.get(), is(customerList.get(8)));
}
Expand Down
14 changes: 10 additions & 4 deletions stream-api/src/test/java/stream/api/Exercise4Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

import static org.hamcrest.Matchers.is;
Expand All @@ -23,7 +24,7 @@ public void firstRegistrant() {
* Find the first customer who registered this online store by using {@link Stream#findFirst}
* The customerList are ascending ordered by registered timing.
*/
Optional<Customer> firstCustomer = null;
Optional<Customer> firstCustomer = customerList.stream().findFirst();

assertThat(firstCustomer.get(), is(customerList.get(0)));
}
Expand All @@ -35,7 +36,9 @@ public void isThereAnyoneOlderThan40() {
/**
* Check whether any customer older than 40 exists or not, by using {@link Stream#anyMatch}
*/
boolean olderThan40Exists = true;
final int ageMax = 40;
Predicate<Customer> plusDe40 = customer -> {return customer.getAge() > ageMax;};
boolean olderThan40Exists = customerList.stream().anyMatch(plusDe40);

assertThat(olderThan40Exists, is(false));
}
Expand All @@ -47,7 +50,9 @@ public void isEverybodyOlderThan20() {
/**
* Check whether all customer are older than 20 or not, by using {@link Stream#allMatch}
*/
boolean allOlderThan20 = false;
final int ageMax = 20;
Predicate<Customer> plusDe20 = customer -> {return customer.getAge() > ageMax;};
boolean allOlderThan20 = customerList.stream().allMatch(plusDe20);

assertThat(allOlderThan20, is(true));
}
Expand All @@ -60,7 +65,8 @@ public void everyoneWantsSomething() {
* Confirm that none of the customer has empty list for their {@link Customer.wantToBuy}
* by using {@link Stream#noneMatch}
*/
boolean everyoneWantsSomething = false;
Predicate<Customer> hasEmptyList = customer -> {return customer.getWantToBuy().isEmpty();};
boolean everyoneWantsSomething = customerList.stream().noneMatch(hasEmptyList);

assertThat(everyoneWantsSomething, is(true));
}
Expand Down
16 changes: 11 additions & 5 deletions stream-api/src/test/java/stream/api/Exercise5Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand All @@ -28,7 +30,9 @@ public void nameList() {
/**
* Create a list of customer names by using {@link Stream#collect} and {@link Collectors#toList}
*/
List<String> nameList = null;
Function<Customer, String> getNameFunction = c -> {return c.getName();};

List<String> nameList = customerList.stream().map(getNameFunction).collect(Collectors.toList());

assertThat(nameList, contains("Joe", "Steven", "Patrick", "Diana", "Chris", "Kathy", "Alice", "Andrew",
"Martin", "Amy"));
Expand All @@ -41,7 +45,8 @@ public void ageSet() {
/**
* Create a set of customer age by using {@link Stream#collect} and {@link Collectors#toSet}
*/
Set<Integer> ageSet = null;
Function<Customer, Integer> getAgeFunction = c -> {return c.getAge();};
Set<Integer> ageSet = customerList.stream().map(getAgeFunction).collect(Collectors.toSet());

assertThat(ageSet, hasSize(9));
assertThat(ageSet, hasItems(21, 22, 26, 27, 28, 32, 35, 36, 38));
Expand All @@ -54,7 +59,8 @@ public void nameInCsv() {
/**
* Create a csv string of customer names in brackets "[]" by using {@link Collectors#joining}
*/
String string = null;
Function<Customer, String> getNameFunction = c -> {return c.getName();};
String string = customerList.stream().map(getNameFunction).collect(Collectors.joining(",","[","]"));

assertThat(string, is("[Joe,Steven,Patrick,Diana,Chris,Kathy,Alice,Andrew,Martin,Amy]"));
}
Expand All @@ -67,7 +73,7 @@ public void oldestCustomer() {
* Get the oldest customer by using {@link Collectors#maxBy}.
* Don't use any intermediate operations.
*/
Optional<Customer> oldestCustomer = null;
Optional<Customer> oldestCustomer = customerList.stream().collect(Collectors.maxBy((c1, c2) -> c1.getAge().compareTo(c2.getAge())));

assertThat(oldestCustomer.get(), is(customerList.get(3)));
}
Expand All @@ -80,7 +86,7 @@ public void ageDistribution() {
* Create a map of age as key and number of customers as value
* using {@link Collectors#groupingBy} and {@link Collectors#counting}
*/
Map<Integer, Long> ageDistribution = null;
Map<Integer, Long> ageDistribution = customerList.stream().collect(Collectors.groupingBy(Customer::getAge, Collectors.counting()));

assertThat(ageDistribution.size(), is(9));
ageDistribution.forEach((k, v) -> {
Expand Down
4 changes: 2 additions & 2 deletions stream-api/src/test/java/stream/api/Exercise6Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public void streamFromValues() {
/**
* Create a stream with string values "a" "b" "c" by using {@link Stream#of}
*/
Stream<String> abcStream = null;
Stream<String> abcStream = Stream.of("a","b","c");

List<String> abcList = abcStream.collect(Collectors.toList());
assertThat(abcList, contains("a", "b", "c"));
Expand All @@ -29,7 +29,7 @@ public void numberStream() {
/**
* Create a stream only with multiples of 3, starting from 0, size of 10, by using {@link Stream#iterate}
*/
Stream<Integer> numbers = null;
Stream<Integer> numbers = Stream.iterate(0,integer -> integer+3).limit(10);

List<Integer> numbersList = numbers.collect(Collectors.toList());
assertThat(numbersList, contains(0, 3, 6, 9, 12, 15, 18, 21, 24, 27));
Expand Down
16 changes: 12 additions & 4 deletions stream-api/src/test/java/stream/api/Exercise7Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
import common.test.tool.annotation.Easy;
import common.test.tool.dataset.ClassicOnlineStore;
import common.test.tool.entity.Customer;
import common.test.tool.entity.Item;
import common.test.tool.entity.Shop;

import org.junit.Test;

import java.util.List;
import java.util.OptionalDouble;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.function.ToLongBiFunction;
import java.util.function.ToLongFunction;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
Expand All @@ -26,8 +31,9 @@ public void averageAge() {
* Create {@link IntStream} with customer ages by using {@link Stream#mapToInt}
* Then calculate the average of ages by using {@link IntStream#average}
*/
IntStream ageStream = null;
OptionalDouble average = null;
ToIntFunction<Customer> ageFunction = c->c.getAge();
IntStream ageStream = customerList.stream().mapToInt(ageFunction);
OptionalDouble average = ageStream.average();

assertThat(average.getAsDouble(), is(28.7));
}
Expand All @@ -40,8 +46,10 @@ public void howMuchToBuyAllItems() {
* Create {@link LongStream} with all items' prices using {@link Stream#mapToLong}
* Then calculate the sum of prices using {@link LongStream#sum}
*/
LongStream priceStream = null;
long priceSum = 0;
ToIntFunction<Item> itemPriceFunction = item -> item.getPrice();
ToLongFunction<Shop> itemsPriceFunction = shop -> shop.getItemList().stream().mapToInt(itemPriceFunction).sum();
LongStream priceStream = shopList.stream().mapToLong(itemsPriceFunction);
long priceSum = priceStream.sum();

assertThat(priceSum, is(60930L));
}
Expand Down