fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone {
  9. public static void main(String[] args) {
  10. Random rnd = new Random();
  11.  
  12. ArrayList<Integer> collection = new ArrayList();
  13. for (int i = 0; i < 5000000; i++) {
  14. collection.add(rnd.nextInt(5000000));
  15. }
  16.  
  17. TreeSet<Integer> minValues = new TreeSet<Integer>();
  18. TreeSet<Integer> maxValues = new TreeSet<Integer>();
  19.  
  20. collection.stream().forEach((v) -> {
  21. handleMin(minValues, v);
  22. handleMax(maxValues, v);
  23. });
  24.  
  25. minValues.stream().forEach((v) -> System.out.println("min = " + v));
  26. maxValues.stream().forEach((v) -> System.out.println("max = " + v));
  27. }
  28.  
  29. public static void handleMin(TreeSet<Integer> values, Integer value) {
  30. if (values.isEmpty() || value < values.last()) {
  31. values.add(value);
  32.  
  33. }
  34.  
  35. if (values.size() > 5) {
  36. values.pollLast();
  37. }
  38. }
  39.  
  40. public static void handleMax(TreeSet<Integer> values, Integer value) {
  41. if (values.isEmpty() || value > values.first()) {
  42. values.add(value);
  43.  
  44. }
  45.  
  46. if (values.size() > 5) {
  47. values.pollFirst();
  48. }
  49. }
  50. }
Success #stdin #stdout 0.46s 200796KB
stdin
Standard input is empty
stdout
min = 0
min = 2
min = 3
min = 5
min = 6
max = 4999992
max = 4999993
max = 4999995
max = 4999996
max = 4999997