stream

стримы

Источник данных

Оператор 1

Оператор 2

...

Оператор n

Терминальный оператор

public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max()
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max((o1, o2) -> {
        return o1 == o2 ? 0 : o1 < o2 ? -1 : 1;
    });
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max((o1, o2) -> o1 == o2 ? 0 : o1 < o2 ? -1 : 1);
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max((o1, o2) -> o1.compareTo(o2));
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max(Integer::compareTo);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max(Integer::compareTo);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max(Integer::compareTo);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    stream.max(Integer::compareTo);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    if (max.isPresent()) {
        // выводим элемент
    }
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    if (max.isPresent()) {
        System.out.println(max.get());
    }
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    max.ifPresent(x -> {
        System.out.println(x);
    });
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    max.ifPresent(System.out::println);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    max.ifPresent(System.out::println);
}

public static void myPrint(Integer value) {
        
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    max.ifPresent(System.out::println);
}

public static void myPrint(Integer value) {
    System.out.println(value);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
    max.ifPresent(Main::myPrint);
}

public static void myPrint(Integer value) {
    System.out.println(value);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
     // если значение не будет найдено, вернется -1
    max.orElse(-1);
}

public static void myPrint(Integer value) {
    System.out.println(value);
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
     // если значение не будет найдено, вернется -1
    max.orElse(-1);
    
    max.orElseGet(() -> {
        System.out.println("ничего не нашел возвращаю -1");
        return -1;
    });
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
     // если значение не будет найдено, вернется -1
    max.orElse(-1);
    
    max.orElseGet(() -> {
        System.out.println("ничего не нашел возвращаю -1");
        return -1;
    });
    
    max.orElseThrow(() -> {
        return new Exception("список пуст");
    });
}
public interface Comparable<T> {
	public int compareTo(T obj);
}

class Integer extends Number implements Comparable<Integer> 
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    // создаем ленивый стрим
    Stream<Integer> stream = items.stream();
    
    Optional<Integer> max = stream.max(Integer::compareTo);
    
     // если значение не будет найдено, вернется -1
    max.orElse(-1);
   
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    int max = items.stream()
            .max(Integer::compareTo)
            .orElse(-1);
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    int max = items.stream()
            .max(Integer::compareTo)
            .orElse(-1);
    
    int min = items.stream()
            .min(Integer::compareTo)
            .orElse(-1);            
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
    
    int max = items.stream()
            .max(Integer::compareTo)
            .orElse(-1);
    
    int min = items.stream()
            .min(Integer::compareTo)
            .get(); // выкинет ошибку если элемента нет
}
public static void main(String[] args) {
    ArrayList<Integer> items = new ArrayList<>(
            Arrays.asList(1, 3, 4, 6, 7, 8, 9)
    );
}
public static void main(String[] args) {
     Stream<Integer> stream = Stream.of(1, 3, 4, 6, 7, 8, 9);
}
public static void main(String[] args) {
     Stream<Integer> stream = Stream.of(1, 3, 4, 6, 7, 8, 9);
}
public static void main(String[] args) {
     Stream<Integer> stream = Stream.of(1, 3, 4, 6, 7, 8, 9);
     stream.forEach(System.out::println);
}
public static void main(String[] args) {
     Stream.Builder<Integer> builder = Stream.builder();
     builder.add(1)
            .add(2)
            .add(3)
            .add(4)
            .add(5)
}
public static void main(String[] args) {
     Stream.Builder<Integer> builder = Stream.builder();
     builder.add(1)
            .add(2)
            .add(3)
            .add(4)
            .add(5)
            .build()
}
public static void main(String[] args) {
     Stream.Builder<Integer> builder = Stream.builder();
     builder.add(1)
            .add(2)
            .add(3)
            .add(4)
            .add(5)
            .build()
            .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.generate(() -> {
        return 5;
    });
}
public static void main(String[] args) {
    Stream.generate(() -> 5)
          .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.generate(() -> 5)
          .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.generate(() -> 5)
          .limit(3) // ограничение на количество элементов
          .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.generate(() -> 5)
          .limit(3) // ограничение на количество элементов
          .forEach(System.out::println);
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1);
}

Начальное значение

Расчет очередного значения

public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1);
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .forEach(x -> {
               System.out.printf("Считаю %s\n", x);
           });
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .forEach(x -> {
               System.out.printf("Считаю %s\n", x);
           });
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .limit(7)
           .forEach(x -> {
               System.out.printf("Считаю %s\n", x);
           });
}

Как вывести значения от 3 до 10?

public static void main(String[] args) {
     Stream.iterate(3, x -> x + 1)
           .limit(7)
           .forEach(x -> {
               System.out.printf("Считаю %s\n", x);
           });
}

Как вывести значения от 3 до 10?

public static void main(String[] args) {
     Stream.iterate(3, x -> x + 1)
           .limit(8)
           .forEach(x -> {
               System.out.printf("Считаю %s\n", x);
           });
}
public static void main(String[] args) {
     Stream.iterate(3, x -> x + 1)
           .limit(8)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(x -> {
               // ???
           });
}
public static void main(String[] args) {
     Stream.iterate(3, x -> x + 1)
           .limit(8)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(x -> {
               System.out.println(x);
           });
}
public static void main(String[] args) {
     Stream.iterate(3, x -> x + 1)
           .limit(8)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(System.out::println);
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .limit(8)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(System.out::println);
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .skip(2)
           .limit(8)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(System.out::println);
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .skip(2)
           .limit(8)
           .peek(System.out::println)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(System.out::println);
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .skip(2)
           .limit(8)
           .peek(System.out::println)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(System.out::println)
           .map(x -> x); // так нельзя
}
public static void main(String[] args) {
     Stream.iterate(1, x -> x + 1)
           .skip(2)
           .limit(8)
           .peek(System.out::println)
           .map(x -> String.format("Считаю %s", x)) 
           .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .distinct()
            .forEach(System.out::println);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .distinct()
            .count();
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .distinct()
            .count(); // вернет число
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .count(); // вернет число
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .count(); // вернет 5
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .sum();
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .sum(); // нет такого метода
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(?, ?);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(0, ?);
}

Начальное значение

Функция сумматор вида BiFunction<T, T, T>

  • 1ый аргумент - предыдущее накопленное значение
  • 2ой аргумент - очередной элемент последовательности
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(0, (sum, x) -> {
                return sum + x;
            });
}

Начальное значение

Функция сумматор вида BiFunction<T, T, T>

  • 1ый аргумент - предыдущее накопленное значение
  • 2ой аргумент - очередной элемент последовательности
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(0, (sum, x) -> {
                System.out.println(sum);
                return sum + x;
            });
}
public static void main(String[] args) {
    System.out.println(
        Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
                .filter(x -> x % 2 == 0)
                .reduce(0, (sum, x) -> {
                    System.out.println(sum);
                    return sum + x;
                })
    );
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(?, ?);
}

Как рассчитать произведение?

public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, ?);
}

Как рассчитать произведение?

public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> ?);
}

Как рассчитать произведение?

public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> prod * x);
}

Как рассчитать произведение?

public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> prod * x);
}

Как рассчитать произведение?

public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> prod * x);
}

Как рассчитать произведение?

public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> prod * x);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> prod * x);
}
public static void main(String[] args) {
    Stream.of(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 1)
            .filter(x -> x % 2 == 0)
            .reduce(1, (prod, x) -> prod * x);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted();
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted()
            .forEach(System.out::println);
}
public interface Comparable<T> {
	int compareTo(T obj);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted()
            .forEach(System.out::println);
}
public interface Comparable<T> {
	int compareTo(T obj);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted(new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    return o1.compareTo(o2);
                }
            })
            .forEach(System.out::println);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted((o1, o2) -> o1.compareTo(o2))
            .forEach(System.out::println);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted((o1, o2) -> {
                return o1 == o2 ? 0 : o1 < o2 ? -1 : 1;
            })
            .forEach(System.out::println);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted((o1, o2) -> {
                return o1.compareTo(o2);
            })
            .forEach(System.out::println);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted((o1, o2) -> {
                return -o1.compareTo(o2);
            })
            .forEach(System.out::println);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
public static void main(String[] args) {
    Stream.of(4, 3, 1, 6, 5, 2)
            .sorted((o1, o2) -> {
                return -o1.compareTo(o2);
            })
            .forEach(System.out::println);
}
public interface Comparator<T> {
	int compare(T o1, T o2);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    );
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
            .sorted((s1, s2) -> s1.age.compareTo(s2.age))
            .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
            .sorted((s1, s2) -> Integer.compare(s1.age, s2.age))
            .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
            .sorted((s1, s2) -> Integer.compare(s1.age, s2.age))
            .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
            .sorted((s1, s2) -> {
                return s1.secondName.compareTo(s2.secondName)
            })
            .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
            .max();
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
            .max((o1, o2) -> Integer.compare(o1.age, o2.age));
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .distinct()
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .distinct()
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .map(student -> student.group)
        .distinct()
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .map(student -> student.group)
        .distinct()
        .sorted()
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .map(student -> student.group)
        .distinct()
        .sorted()
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(?)
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .anyMatch(student -> student.group == "ИСТБп");
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .allMatch(student -> student.group == "ИСТБп");
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .allMatch(student -> student.group == "ИСТБп");
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .forEach(System.out::println);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .collect(?);
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .collect(Collectors.toList());
}
public static <T>
Collector<T, ?, List<T>> toList() {
    return new Collectors.CollectorImpl<>(
        (Supplier<List<T>>) ArrayList::new,
        List::add,
        (left, right) -> { left.addAll(right); return left; },
        CH_ID
    );
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .collect(Collectors.toList());
}
public static <T>
Collector<T, ?, List<T>> toList() {
    return new Collectors.CollectorImpl<>(
        (Supplier<List<T>>) ArrayList::new,
        List::add,
        (left, right) -> { left.addAll(right); return left; },
        CH_ID
    );
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    List<Student> items = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .filter(student -> student.group == "ИСТБп")
        .collect(Collectors.toList());
}
public static <T>
Collector<T, ?, List<T>> toList() {
    return new Collectors.CollectorImpl<>(
        (Supplier<List<T>>) ArrayList::new,
        List::add,
        (left, right) -> { left.addAll(right); return left; },
        CH_ID
    );
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.toList());
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.groupingBy(???));
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.groupingBy(student -> student.group));
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Map<String, List<Student>> dict = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.groupingBy(student -> student.group));
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Map<String, List<Student>> dict = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.groupingBy(student -> student.group));
        
    for(String key : dict.keySet()) {
        
    }
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Map<String, List<Student>> dict = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.groupingBy(student -> student.group));
        
    for(String key : dict.keySet()) {
        System.out.printf("\nСтуденты из %s\n", key);
    }
}
static class Student {
    public String firstName;
    public String secondName;
    public String group;
    public int age;
}

public static void main(String[] args) {
    Map<String, List<Student>> dict = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
    )
        .collect(Collectors.groupingBy(student -> student.group));
        
    for(String key : dict.keySet()) {
        System.out.printf("\nСтуденты из %s\n", key);
        dict.get(key).forEach(System.out::println);
    }
}
  • Используем items.stream() или Stream.of(1, 2, 3)
  • Используем для работы с данными
    • map - для преобразований
    • filter - для фильтра
    • distinct - для удаления повторов
    • skip - для пропуска лишних значений
    • limit - для ограничения количества
    • sorted - для сортировки
  • ​Используем терминальные операторы
    • ​count - для подсчета количества
    • max(x -> x.fieldName) - для поиска максимума по полю
  • Используем items.stream() или Stream.of(1, 2, 3)
  • Используем для работы с данными
    • map - для преобразований
    • filter - для фильтра
    • distinct - для удаления повторов
    • skip - для пропуска лишних значений
    • limit - для ограничения количества
    • sorted - для сортировки
  • ​Используем терминальные операторы
    • ​count - для подсчета количества
    • max(x -> x.fieldName) - для поиска максимума по полю
    • collect(Collectors.toList()) - для сбора в список
    • collect(Collectors.groupingBy(x -> x.fieldName))
    • reduce - для расчета суммы

Если результат -- одно значение,
то получим  в ответ Optional,
доступ к значению осуществляем через get
с проверкой на существование:

Optional<Integer> max = items.stream().max(Integer::compareTo);

if (max.isPresent()) {
   System.out.println(max.get());
}

Если результат -- список
то просто сохраняем в переменную списка

List<Student> students = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
)
        .filter(x -> x.group == "ИСМБ")
        .collect(Collectors.toList());

Если результат -- словарик
то собираем в Map
и обходим значения по ключам

Map<String, List<Student>> dict = Stream.of(
        new Student("Женя", "Пупкин", "ИСТБп", 20),
        new Student("Катя", "Маргариткина", "ИСТБ", 20),
        new Student("Ваня", "Иванов", "ИСМБ", 19),
        new Student("Оля", "Добрая", "ИСТБп", 21)
)
        .collect(Collectors.groupingBy(x -> x.group));

for(String key : dict.keySet()) {
    System.out.printf("\nСтуденты из %s\n", key);
    dict.get(key).forEach(System.out::println);
}

https://annimon.com/article/2778

public class DynamicDict<K, V> {
    ArrayList<K> keys = new ArrayList<>();
    ArrayList<V> values = new ArrayList<>();

    public void put(K key, V value) {
        int iKey = keys.indexOf(key);
        if (iKey == -1) {
            keys.add(key);
            values.add(value);
        } else {
            values.set(iKey, value);
        }
    }

    public V get(K key) {
        int iKey = keys.indexOf(key);
        if (iKey != -1) {
            return values.get(iKey);
        }
        return null;
    }
}

Написать функцию, которая выдает список ключей, значения по которым меньше либо равны аргументу функции

Made with Slides.com