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)
);
}
}