Skip to content

Exercice 1 à 8 #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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 @@ -27,8 +27,9 @@ 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;
/** Done, on a utilisé un filtre*/
Predicate<Customer> richCustomerCondition = customer -> customer.getBudget() > 10000;
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 +46,9 @@ 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;
/** Done, utilisation de map pour apeller une autre fonction*/
Function<Customer, Integer> getAgeFunction = Customer::getAge;
Stream<Integer> ageStream = customerList.stream().map(getAgeFunction);

assertTrue(AssertUtil.isLambda(getAgeFunction));
List<Integer> richCustomer = ageStream.collect(Collectors.toList());
Expand Down
22 changes: 14 additions & 8 deletions stream-api/src/test/java/stream/api/Exercise2Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ 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 = customer -> customer.getAge();
Stream<Integer> sortedAgeStream = customerList.stream().map(getAgeFunction).sorted();

List<Integer> sortedAgeList = sortedAgeStream.collect(Collectors.toList());
assertThat(sortedAgeList, contains(21, 22, 22, 26, 27, 28, 32, 35, 36, 38));
Expand All @@ -39,9 +40,10 @@ public void descSortByAge() {

/**
* Create a stream with descending ordered age values.
* (Person a, Person b) -> b.getName().compareTo(a.getName())
*/
Comparator<Integer> descOrder = null;
Stream<Integer> sortedAgeStream = null;
Comparator<Integer> descOrder = (Integer a, Integer b) -> b.compareTo(a);
Stream<Integer> sortedAgeStream = customerList.stream().map(Customer::getAge).sorted(descOrder);

assertTrue(AssertUtil.isLambda(descOrder));
List<Integer> sortedAgeList = sortedAgeStream.collect(Collectors.toList());
Expand All @@ -54,8 +56,12 @@ public void top3RichCustomer() {

/**
* Create a stream with top 3 rich customers using {@link Stream#limit} to limit the size of the stream
* widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
*/
Stream<String> top3RichCustomerStream = null;
Stream<String> top3RichCustomerStream = customerList.stream().sorted((obj1, obj2) -> obj2.getBudget() - obj1.getBudget()).limit(3).map(Customer::getName);

List<String> top3RichCustomerList = top3RichCustomerStream.collect(Collectors.toList());
assertThat(top3RichCustomerList, contains("Diana", "Andrew", "Chris"));
Expand All @@ -67,8 +73,9 @@ public void distinctAge() {

/**
* Create a stream with distinct age values using {@link Stream#distinct}
* collect(toMap(Person::getName, p -> p, (p, q) -> p)).values();
*/
Stream<Integer> distinctAgeStream = null;
Stream<Integer> distinctAgeStream = customerList.stream().map(Customer::getAge).distinct();

List<Integer> distinctAgeList = distinctAgeStream.collect(Collectors.toList());
assertThat(distinctAgeList, contains(22, 27, 28, 38, 26, 32, 35, 21, 36));
Expand All @@ -82,9 +89,8 @@ 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 -> customer.getWantToBuy().stream();
Stream<String> itemStream = customerList.stream().flatMap(getItemStream).map(Item::getName);
assertTrue(AssertUtil.isLambda(getItemStream));
List<String> itemList = itemStream.collect(Collectors.toList());
assertThat(itemList,
Expand Down
14 changes: 9 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,8 @@ 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 -> customer.getWantToBuy().stream();
long sum = customerList.stream().flatMap(getItemStream).map(Item::getName).count();

assertThat(sum, is(32L));
}
Expand All @@ -35,9 +38,10 @@ public void richestCustomer() {
/**
* Find the richest customer's budget by using {@link Stream#max} and {@link Comparator#naturalOrder}
* Don't use {@link Stream#sorted}
* comparing(Integer::getName, naturalOrder());
*/
Comparator<Integer> comparator = null;
Optional<Integer> richestCustomer = null;
Comparator <Integer> comparator = Comparator.naturalOrder();
Optional<Integer> richestCustomer = customerList.stream().map(Customer::getBudget).max(comparator);

assertThat(comparator.getClass().getSimpleName(), is("NaturalOrderComparator"));
assertThat(richestCustomer.get(), is(12000));
Expand All @@ -51,8 +55,8 @@ 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;
Comparator<Customer> comparator = (Customer c1, Customer c2) -> c1.getAge() - c2.getAge();
Optional<Customer> youngestCustomer = customerList.stream().min(comparator);

assertThat(youngestCustomer.get(), is(customerList.get(8)));
}
Expand Down
8 changes: 4 additions & 4 deletions stream-api/src/test/java/stream/api/Exercise4Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,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 +35,7 @@ public void isThereAnyoneOlderThan40() {
/**
* Check whether any customer older than 40 exists or not, by using {@link Stream#anyMatch}
*/
boolean olderThan40Exists = true;
boolean olderThan40Exists = customerList.stream().anyMatch(customer -> customer.getAge() > 40);

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

assertThat(allOlderThan20, is(true));
}
Expand All @@ -60,7 +60,7 @@ 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;
boolean everyoneWantsSomething = customerList.stream().map(customer -> customer.getWantToBuy()).noneMatch(items -> items.isEmpty());

assertThat(everyoneWantsSomething, is(true));
}
Expand Down
15 changes: 6 additions & 9 deletions stream-api/src/test/java/stream/api/Exercise5Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@

import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand All @@ -28,7 +25,7 @@ public void nameList() {
/**
* Create a list of customer names by using {@link Stream#collect} and {@link Collectors#toList}
*/
List<String> nameList = null;
List<String> nameList = customerList.stream().map(Customer::getName).collect(Collectors.toList());

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

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

assertThat(string, is("[Joe,Steven,Patrick,Diana,Chris,Kathy,Alice,Andrew,Martin,Amy]"));
}
Expand All @@ -67,7 +64,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((Customer c1, Customer c2) -> c1.getAge() - c2.getAge()));

assertThat(oldestCustomer.get(), is(customerList.get(3)));
}
Expand All @@ -80,7 +77,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
6 changes: 4 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,9 @@ 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, n -> n + 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
11 changes: 7 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,6 +3,7 @@
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;
Expand All @@ -26,8 +27,8 @@ 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;
IntStream ageStream = customerList.stream().mapToInt(Customer::getAge);
OptionalDouble average = ageStream.average();

assertThat(average.getAsDouble(), is(28.7));
}
Expand All @@ -39,9 +40,11 @@ public void howMuchToBuyAllItems() {
/**
* Create {@link LongStream} with all items' prices using {@link Stream#mapToLong}
* Then calculate the sum of prices using {@link LongStream#sum}
* Function<Customer, Stream<Item>> getItemStream = customer -> customer.getWantToBuy().stream();
Stream<String> itemStream = customerList.stream().flatMap(getItemStream).map(Item::getName);
*/
LongStream priceStream = null;
long priceSum = 0;
LongStream priceStream = shopList.stream().flatMap(shop -> shop.getItemList().stream()).mapToLong(Item::getPrice);
long priceSum = priceStream.sum();

assertThat(priceSum, is(60930L));
}
Expand Down
7 changes: 5 additions & 2 deletions stream-api/src/test/java/stream/api/Exercise8Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.hamcrest.Matchers.hasItems;
Expand All @@ -27,8 +28,10 @@ public void itemsNotOnSale() {
/**
* Create a set of item names that are in {@link Customer.wantToBuy} but not on sale in any shop.
*/
List<String> itemListOnSale = null;
Set<String> itemSetNotOnSale = null;

/** Essai */
List<String> itemListOnSale = shopStream.map(Shop::getItemList).flatMap(List::stream).map(Item::getName).collect(Collectors.toList());
Set<String> itemSetNotOnSale = customerStream.map(Customer::getWantToBuy).flatMap(List::stream).map(Item::getName).collect(Collectors.toSet());

assertThat(itemSetNotOnSale, hasSize(3));
assertThat(itemSetNotOnSale, hasItems("bag", "pants", "coat"));
Expand Down