diff --git a/stream-api/src/test/java/stream/api/Exercise1Test.java b/stream-api/src/test/java/stream/api/Exercise1Test.java index 368443e..5bdb38a 100644 --- a/stream-api/src/test/java/stream/api/Exercise1Test.java +++ b/stream-api/src/test/java/stream/api/Exercise1Test.java @@ -19,6 +19,8 @@ public class Exercise1Test extends ClassicOnlineStore { + private final static int BUDGET = 10000; + @Easy @Test public void findRichCustomers() { List customerList = this.mall.getCustomerList(); @@ -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 richCustomerCondition = null; - Stream richCustomerStream = null; + Predicate richCustomerCondition = (c)-> c.getBudget() > BUDGET; + Stream richCustomerStream = customerList.stream().filter(richCustomerCondition); assertTrue("Solution for Predicate should be lambda expression", AssertUtil.isLambda(richCustomerCondition)); List richCustomer = richCustomerStream.collect(Collectors.toList()); @@ -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 getAgeFunction = null; - Stream ageStream = null; + Function getAgeFunction = c ->{ return c.getAge();}; + Stream ageStream = customerList.stream().map(getAgeFunction); assertTrue(AssertUtil.isLambda(getAgeFunction)); List richCustomer = ageStream.collect(Collectors.toList()); diff --git a/stream-api/src/test/java/stream/api/Exercise2Test.java b/stream-api/src/test/java/stream/api/Exercise2Test.java index a7f8956..144c084 100644 --- a/stream-api/src/test/java/stream/api/Exercise2Test.java +++ b/stream-api/src/test/java/stream/api/Exercise2Test.java @@ -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; @@ -19,6 +20,9 @@ public class Exercise2Test extends ClassicOnlineStore { + private Function getAgeFunction = c ->{return c.getAge();}; + private Function getNameFunction = c ->{return c.getName();}; + @Easy @Test public void sortByAge() { List customerList = this.mall.getCustomerList(); @@ -27,7 +31,16 @@ public void sortByAge() { * Create a stream with ascending ordered age values. * Use {@link Stream#sorted} to sort them. */ - Stream sortedAgeStream = null; + //Function getAgeFunction = c ->{return c.getAge();}; + + Comparator comparator = (Customer c1, Customer c2)-> { + return c1.getAge().compareTo(c2.getAge()); + }; + + //Collections.sort(customerList); + + Stream sortedAgeStream = customerList.stream().sorted(comparator).map(getAgeFunction); + List sortedAgeList = sortedAgeStream.collect(Collectors.toList()); assertThat(sortedAgeList, contains(21, 22, 22, 26, 27, 28, 32, 35, 36, 38)); @@ -40,8 +53,13 @@ public void descSortByAge() { /** * Create a stream with descending ordered age values. */ - Comparator descOrder = null; - Stream sortedAgeStream = null; + // + //Function getAgeFunction = c ->{return c.getAge();}; + + Comparator descOrder = (Integer nb1, Integer nb2)->{ + return - nb1.compareTo(nb2); + }; + Stream sortedAgeStream = customerList.stream().map(getAgeFunction).sorted(descOrder); assertTrue(AssertUtil.isLambda(descOrder)); List sortedAgeList = sortedAgeStream.collect(Collectors.toList()); @@ -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 top3RichCustomerStream = null; + + Comparator comparator = (Customer c1, Customer c2)-> { + return -c1.getBudget().compareTo(c2.getBudget()); + }; + + Stream top3RichCustomerStream = customerList.stream().sorted(comparator).map(getNameFunction).limit(3); List top3RichCustomerList = top3RichCustomerStream.collect(Collectors.toList()); assertThat(top3RichCustomerList, contains("Diana", "Andrew", "Chris")); @@ -68,7 +91,7 @@ public void distinctAge() { /** * Create a stream with distinct age values using {@link Stream#distinct} */ - Stream distinctAgeStream = null; + Stream distinctAgeStream = customerList.stream().map(getAgeFunction).distinct(); List distinctAgeList = distinctAgeStream.collect(Collectors.toList()); assertThat(distinctAgeList, contains(22, 27, 28, 38, 26, 32, 35, 21, 36)); @@ -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> getItemStream = null; - Stream itemStream = null; + Function> getItemStream = customer -> {return customer.getWantToBuy().stream();}; + Function getNameItemFunction = item -> item.getName(); + Stream itemStream = customerList.stream().flatMap(getItemStream).map(getNameItemFunction); assertTrue(AssertUtil.isLambda(getItemStream)); List itemList = itemStream.collect(Collectors.toList()); diff --git a/stream-api/src/test/java/stream/api/Exercise3Test.java b/stream-api/src/test/java/stream/api/Exercise3Test.java index 04dfdf3..826ce27 100644 --- a/stream-api/src/test/java/stream/api/Exercise3Test.java +++ b/stream-api/src/test/java/stream/api/Exercise3Test.java @@ -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; @@ -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> getItemStream = customer -> { return customer.getWantToBuy().stream();}; + Function getItemFunction = item -> { return item.getName();}; + long sum = customerList.stream().flatMap(getItemStream).map(getItemFunction).count(); assertThat(sum, is(32L)); } @@ -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 comparator = null; - Optional richestCustomer = null; + + Function getBudgetFunction = customer -> {return customer.getBudget();}; +// Comparator comparator = (nb1, nb2) -> {return nb1.compareTo(nb2);}; + Comparator comparator = Comparator.naturalOrder() ; + Optional richestCustomer = customerList.stream().map(getBudgetFunction).max(comparator); assertThat(comparator.getClass().getSimpleName(), is("NaturalOrderComparator")); assertThat(richestCustomer.get(), is(12000)); @@ -51,8 +58,9 @@ public void youngestCustomer() { * Find the youngest customer by using {@link Stream#min} * Don't use {@link Stream#sorted} */ - Comparator comparator = null; - Optional youngestCustomer = null; + //Function getAgeFunction = customer -> {return customer.getAge();}; + Comparator comparator = (c1, c2) -> {return c1.getAge().compareTo(c2.getAge());}; + Optional youngestCustomer = customerList.stream().min(comparator); assertThat(youngestCustomer.get(), is(customerList.get(8))); } diff --git a/stream-api/src/test/java/stream/api/Exercise4Test.java b/stream-api/src/test/java/stream/api/Exercise4Test.java index 69898e4..7b95e69 100644 --- a/stream-api/src/test/java/stream/api/Exercise4Test.java +++ b/stream-api/src/test/java/stream/api/Exercise4Test.java @@ -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; @@ -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 firstCustomer = null; + Optional firstCustomer = customerList.stream().findFirst(); assertThat(firstCustomer.get(), is(customerList.get(0))); } @@ -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 plusDe40 = customer -> {return customer.getAge() > ageMax;}; + boolean olderThan40Exists = customerList.stream().anyMatch(plusDe40); assertThat(olderThan40Exists, is(false)); } @@ -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 plusDe20 = customer -> {return customer.getAge() > ageMax;}; + boolean allOlderThan20 = customerList.stream().allMatch(plusDe20); assertThat(allOlderThan20, is(true)); } @@ -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 hasEmptyList = customer -> {return customer.getWantToBuy().isEmpty();}; + boolean everyoneWantsSomething = customerList.stream().noneMatch(hasEmptyList); assertThat(everyoneWantsSomething, is(true)); } diff --git a/stream-api/src/test/java/stream/api/Exercise5Test.java b/stream-api/src/test/java/stream/api/Exercise5Test.java index dc41f32..6b5ebda 100644 --- a/stream-api/src/test/java/stream/api/Exercise5Test.java +++ b/stream-api/src/test/java/stream/api/Exercise5Test.java @@ -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; @@ -28,7 +30,9 @@ public void nameList() { /** * Create a list of customer names by using {@link Stream#collect} and {@link Collectors#toList} */ - List nameList = null; + Function getNameFunction = c -> {return c.getName();}; + + List nameList = customerList.stream().map(getNameFunction).collect(Collectors.toList()); assertThat(nameList, contains("Joe", "Steven", "Patrick", "Diana", "Chris", "Kathy", "Alice", "Andrew", "Martin", "Amy")); @@ -41,7 +45,8 @@ public void ageSet() { /** * Create a set of customer age by using {@link Stream#collect} and {@link Collectors#toSet} */ - Set ageSet = null; + Function getAgeFunction = c -> {return c.getAge();}; + Set ageSet = customerList.stream().map(getAgeFunction).collect(Collectors.toSet()); assertThat(ageSet, hasSize(9)); assertThat(ageSet, hasItems(21, 22, 26, 27, 28, 32, 35, 36, 38)); @@ -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 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]")); } @@ -67,7 +73,7 @@ public void oldestCustomer() { * Get the oldest customer by using {@link Collectors#maxBy}. * Don't use any intermediate operations. */ - Optional oldestCustomer = null; + Optional oldestCustomer = customerList.stream().collect(Collectors.maxBy((c1, c2) -> c1.getAge().compareTo(c2.getAge()))); assertThat(oldestCustomer.get(), is(customerList.get(3))); } @@ -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 ageDistribution = null; + Map ageDistribution = customerList.stream().collect(Collectors.groupingBy(Customer::getAge, Collectors.counting())); assertThat(ageDistribution.size(), is(9)); ageDistribution.forEach((k, v) -> { diff --git a/stream-api/src/test/java/stream/api/Exercise6Test.java b/stream-api/src/test/java/stream/api/Exercise6Test.java index 3003eb1..a4ddc31 100644 --- a/stream-api/src/test/java/stream/api/Exercise6Test.java +++ b/stream-api/src/test/java/stream/api/Exercise6Test.java @@ -18,7 +18,7 @@ public void streamFromValues() { /** * Create a stream with string values "a" "b" "c" by using {@link Stream#of} */ - Stream abcStream = null; + Stream abcStream = Stream.of("a","b","c"); List abcList = abcStream.collect(Collectors.toList()); assertThat(abcList, contains("a", "b", "c")); @@ -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 numbers = null; + Stream numbers = Stream.iterate(0,integer -> integer+3).limit(10); List numbersList = numbers.collect(Collectors.toList()); assertThat(numbersList, contains(0, 3, 6, 9, 12, 15, 18, 21, 24, 27)); diff --git a/stream-api/src/test/java/stream/api/Exercise7Test.java b/stream-api/src/test/java/stream/api/Exercise7Test.java index 6eec18a..a20265d 100644 --- a/stream-api/src/test/java/stream/api/Exercise7Test.java +++ b/stream-api/src/test/java/stream/api/Exercise7Test.java @@ -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; @@ -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 ageFunction = c->c.getAge(); + IntStream ageStream = customerList.stream().mapToInt(ageFunction); + OptionalDouble average = ageStream.average(); assertThat(average.getAsDouble(), is(28.7)); } @@ -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 itemPriceFunction = item -> item.getPrice(); + ToLongFunction itemsPriceFunction = shop -> shop.getItemList().stream().mapToInt(itemPriceFunction).sum(); + LongStream priceStream = shopList.stream().mapToLong(itemsPriceFunction); + long priceSum = priceStream.sum(); assertThat(priceSum, is(60930L)); }