/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
	public static void main(String[] args) {
        Random rnd = new Random();

        ArrayList<Integer> collection = new ArrayList();
        for (int i = 0; i < 5000000; i++) {
            collection.add(rnd.nextInt(5000000));
        }

        TreeSet<Integer> minValues = new TreeSet<Integer>();
        TreeSet<Integer> maxValues = new TreeSet<Integer>();

        collection.stream().forEach((v) -> {
            handleMin(minValues, v);
            handleMax(maxValues, v);
        });

        minValues.stream().forEach((v) -> System.out.println("min = " + v));
        maxValues.stream().forEach((v) -> System.out.println("max = " + v));
    }

    public static void handleMin(TreeSet<Integer> values, Integer value) {
        if (values.isEmpty() || value < values.last()) {
            values.add(value);

        }

        if (values.size() > 5) {
            values.pollLast();
        }
    }

    public static void handleMax(TreeSet<Integer> values, Integer value) {
        if (values.isEmpty() || value > values.first()) {
            values.add(value);

        }

        if (values.size() > 5) {
            values.pollFirst();
        }
    }
}