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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
package com.company; import java.util.*; import java.util.stream.Collectors; public class Person { private final String name; private final int age; private Gender gender; public enum Gender { MALE, FEMALE } public Person(String name, int age, Gender gender) { this.name = name; this.age = age; this.gender = gender; } public String getName() { return name; } public int getAge() { return age; } public Gender getGender() { return gender; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender=" + gender + '}'; } public static void main(String[] args) { List<Person> people = getPeople(); List<Person> females = people.stream() //tylko FEMALE .filter(person -> person.gender.equals(Gender.FEMALE)) .collect(Collectors.toList()); females.forEach(System.out::println); List<Person> sorted = people.stream() //posortowane wg wieku .sorted(Comparator.comparing(Person::getAge)) //po dodaniu .reversed()) odwróci listę .collect(Collectors.toList()); sorted.forEach(System.out::println); boolean allMatch = people.stream() //czy wszyscy z listy spełniają warunek wiek >=28 .allMatch(person -> person.getAge()>=28); System.out.println(allMatch); boolean anyMatch = people.stream() //czy ktokolwiek spełnia warunek wiek >=20 .anyMatch(person -> person.getAge()==20); System.out.println(anyMatch); boolean noneMatch = people.stream() //czy nikt nie spełnia warunku name.equals("Harry Poter") .noneMatch(person -> person.getName().equals("Harry Poter")); System.out.println(noneMatch); people.stream() //osoba o największym wieku .max(Comparator.comparing(Person::getAge)) .ifPresent(System.out::println); people.stream() //osoba o najmniejszym wieku .min(Comparator.comparing(Person::getAge)) .ifPresent(System.out::println); } private static List<Person> getPeople() { return Arrays.asList( new Person("James Bond", 20, Gender.MALE), new Person("Alina Smith", 33, Gender.FEMALE), new Person("Helen White", 28, Gender.FEMALE), new Person("Alan Black", 19, Gender.MALE) ); } } |