ukryj menu
SPEC
aktualizacja: 2022-04-29 09:13:05
1. Streams APIPojawiło się w Javie 8
Stream API stosowane jest do operacji na kolekcjach
Wejściem dla Stream-ów moga być Collections, Arrays, I/O Stream nie zmienia oryginalnej struktury danych, zwraca tylko rezultat danej operacji na niej
Każda pośrednia operacja zwraca rezultat na którym można dalej operować
Niektóre operacje kończą Streama
Streamy wykorzystują lambdy
podstawowe operacje na streamach
a) obiekt Stream, toList
List<String> names = Arrays.asList("Aaa","Bbb","Acc");
Stream<String> result = names.stream();
System.out.println(result.toList());kopiuj
b) map
zwraca stream z rezultatem funkcji operującej na elementach streama
List<Integer> numbers = Arrays.asList(1,2,3);
Stream<Integer> square = numbers.stream()
.map(x -> x * x);
System.out.println(square.toList());kopiuj
Stream<Integer> square = numbers.stream()
.map(x -> x * x);
System.out.println(square.toList());kopiuj
c) filter
wybieranie elementów streama (na literę A)
List<String> names = Arrays.asList("Aaa","Bbb","Acc");
Stream<String> result = names.stream()
.filter(s->s.startsWith("A"));
System.out.println(result.toList());kopiuj
Stream<String> result = names.stream()
.filter(s->s.startsWith("A"));
System.out.println(result.toList());kopiuj
d) sorted
sortowanie elementów streama
List<String> names = Arrays.asList("Aaa","Bbb","Acc");
Stream<String> result = names.stream()
.sorted();
System.out.println(result.toList());kopiuj
Stream<String> result = names.stream()
.sorted();
System.out.println(result.toList());kopiuj
e) collect
metoda collect służy do zwracania wyniku operacji pośrednich wykonanych na strumieniu
List<Integer> number = Arrays.asList(2,3,4,5,3);
Set<Integer> square = number.stream()
.map(x->x*x)
.collect(Collectors.toSet());
System.out.println(square);kopiuj
Set<Integer> square = number.stream()
.map(x->x*x)
.collect(Collectors.toSet());
System.out.println(square);kopiuj
f) forEach
iteracja po elementach streama
List<Integer> numbers = Arrays.asList(2,3,4,5);
numbers.stream()
.map( x -> x * x)
.forEach(y->System.out.println("y="+y));kopiuj
2. Streams - przykłady pracy z obiektami
class Employee {
public Employee(int id, String name, Double salary) {
}
}kopiuj
lista
List<Employee> list = Arrays.asList(
new Employee(1, "Jeff Bezos", 100000.0),
new Employee(2, "Bill Gates", 200000.0),
new Employee(3, "Mark Zuckerberg", 300000.0)
);kopiuj
iteracja
list.stream()
.forEach(employee -> System.out.println("employee: "+employee));kopiuj
.forEach(employee -> System.out.println("employee: "+employee));kopiuj
Stream<Employee> result = list.stream()
.filter(employee -> employee.getId()==1);
System.out.println(result.toList());kopiuj
skip, limit
Stream<Employee> result = list.stream()
.skip(2)
.limit(2);
System.out.println(result.toList());kopiuj
.skip(2)
.limit(2);
System.out.println(result.toList());kopiuj
generate, limit
Stream
.generate(() -> Math.random())
.limit(4)
.forEach(aDouble -> System.out.println(aDouble));kopiuj
.generate(() -> Math.random())
.limit(4)
.forEach(aDouble -> System.out.println(aDouble));kopiuj
generate 2
Stream<Double> rands = Stream
.generate(() -> Math.random())
.limit(4);
System.out.println(rands.toList());kopiuj
anyMatch
podczas wyszukiwania można sprawdzić true/false czy znaleziono dane o założonych kryteriach
w tym wypadku czy którykolwiek element listy * 2 = 4
List<Integer> list = Arrays.asList(1,2,3,45);
boolean test = list.stream()
.anyMatch( n -> n * 2 == 4);
System.out.println(test);kopiuj
boolean test = list.stream()
.anyMatch( n -> n * 2 == 4);
System.out.println(test);kopiuj
distinct, sorted
wybierz niepowtarzające się i posortuj
List<Integer> numbers = Arrays.asList(9, 8, 0, 5, 6, 2, 3, 4, 9, 0, 6, 2, 3, 5, 0, 9, 6, 3, 4, 9, 3);
List<Integer> result = numbers.stream()
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println(result);kopiuj
List<Integer> result = numbers.stream()
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println(result);kopiuj
reduce
List<Integer> numbers = asList(1, 2, 3, 4, 5, 6);
numbers.stream()
.reduce((a, b) -> a + b).ifPresent(System.out::println);kopiuj
numbers.stream()
.reduce((a, b) -> a + b).ifPresent(System.out::println);kopiuj
peek
bieżące śledzenie stanu operacji na streamie
List<Integer> numbers = asList(1, 2, 3);
numbers.stream()
.peek(n -> System.out.println("A: " + n))
.map(n -> n + 5)
.peek(n -> System.out.println("B: " + n))
.sorted() // wykonanie powyższych
.map(n -> n + 5)
.peek(n -> System.out.println("C: " + n))
.collect(toList());
kopiuj
numbers.stream()
.peek(n -> System.out.println("A: " + n))
.map(n -> n + 5)
.peek(n -> System.out.println("B: " + n))
.sorted() // wykonanie powyższych
.map(n -> n + 5)
.peek(n -> System.out.println("C: " + n))
.collect(toList());
kopiuj
3. Większy przykład łańcucha operacji na streamach
klasa
class Beverage {
private String name;
private int price;
public Beverage(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
kopiuj
lista
List<Beverage> beverages = Arrays.asList(
new Beverage("Cola", 2),
new Beverage("HipsterCola", 5),
new Beverage("SuperHipsterCola", 5),
new Beverage("UltraSuperHipsterCola", 10),
new Beverage("CheapCola", 2)
kopiuj
);
wyszukane napoje na literę C
List<Beverage> naC = beverages.stream()
.filter(b -> b.getName().startsWith("C"))
.toList();
System.out.println(naC); // [Cola, CheapCola]kopiuj
.filter(b -> b.getName().startsWith("C"))
.toList();
System.out.println(naC); // [Cola, CheapCola]kopiuj
wyszukane droższe niż 5
List<Beverage> ultras = beverages.stream()
.filter(b -> b.getPrice() > 5)
.toList();
System.out.println(ultras);kopiuj
.filter(b -> b.getPrice() > 5)
.toList();
System.out.println(ultras);kopiuj
średnia cena napoju
Double averagePrice = beverages
.stream()
.collect(Collectors.averagingInt(b -> b.getPrice()));
System.out.println(averagePrice); //4.8kopiuj
oferta specjalna : obniżka dla droższych niż 2
String specialOffer = beverages
.stream()
.filter(b -> b.getPrice() > 2)
.map(b -> b.getName())
.collect(Collectors.joining(" i ", "Oferta specjalna na :", " wynosi -20%."));
System.out.println(specialOffer);kopiuj