-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathOptional_01_Test.java
More file actions
53 lines (37 loc) · 1.58 KB
/
Optional_01_Test.java
File metadata and controls
53 lines (37 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package java17.ex01;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import java17.data.Data;
import java17.data.Person;
/**
* Exercice 02 - Filter, Map
*/
public class Optional_01_Test {
class NotPresentException extends RuntimeException {
}
@Test
public void test_optional_ifPresent() throws Exception {
List<Person> persons = Data.buildPersonList(10);
// TODO rechercher dans la liste ci-dessus la 1ère personne ayant 18 ans
// TODO utiliser la méthode "findFirst"
Optional<Person> optPerson = persons.stream().findFirst();
assertThat(optPerson.isPresent(), is(true));
// TODO afficher la personne en question si l'optional contient une personne
System.out.println(optPerson.get().getFirstname());
}
@Test(expected=NotPresentException.class)
public void test_optional_notPresent() throws Exception {
List<Person> persons = Data.buildPersonList(50);
// TODO rechercher dans la liste ci-dessus la 1ère personne ayant 75 ans
// TODO utiliser la méthode "findFirst"
Optional<Person> optPerson = persons.stream().filter(person->person.getAge()==75).findFirst();
assertThat(optPerson.isPresent(), is(false));
Person person = optPerson.orElseThrow(NotPresentException::new);
// TODO si la personne n'existe pas, jeter une exception NotPresentException
// TODO utiliser la méthode "orElseThrow"
}
}