fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.List;
  6. import java.util.function.Function;
  7. import java.util.stream.Stream;
  8. import java.util.Random;
  9.  
  10. import static java.util.Collections.emptyList;
  11. import static java.util.stream.Collectors.toList;
  12. import static java.util.stream.Stream.generate;
  13.  
  14. /* Name of the class has to be "Main" only if the class is public. */
  15. class Ideone
  16. {
  17. public static class MaxAndMinDto {
  18. private final List<Integer> max;
  19. private final List<Integer> min;
  20.  
  21. private MaxAndMinDto(List<Integer> max, List<Integer> min) {
  22. this.max = max;
  23. this.min = min;
  24. }
  25.  
  26. public List<Integer> getMax() {
  27. return max;
  28. }
  29.  
  30. public List<Integer> getMin() {
  31. return min;
  32. }
  33.  
  34. @Override
  35. public String toString() {
  36. return "MaxAndMinDto{max=" + max + ", min=" + min + '}';
  37. }
  38. }
  39.  
  40. public static Function<Stream<Integer>, MaxAndMinDto> findMaxAndMinWithLimit(int limit) {
  41. Comparator<Integer> comparator = Integer::compareTo;
  42. return s -> s
  43. .map(Collections::singletonList)
  44. .map(list -> new MaxAndMinDto(list, list))
  45. .reduce((left, right) -> new MaxAndMinDto(
  46. Stream.concat(left.getMax().stream(), right.getMax().stream())
  47. .sorted(comparator.reversed())
  48. .distinct()
  49. .limit(limit)
  50. .collect(toList()),
  51. Stream.concat(left.getMin().stream(), right.getMin().stream())
  52. .sorted(comparator)
  53. .distinct()
  54. .limit(limit)
  55. .collect(toList())
  56. ))
  57. .orElseGet(() -> new MaxAndMinDto(emptyList(), emptyList()));
  58. }
  59.  
  60. public static void main (String[] args) throws java.lang.Exception
  61. {
  62. int limit = 5;
  63. Random random = new Random();
  64. Stream<Integer> values = generate(random::nextInt).limit(5000000);
  65. MaxAndMinDto maxAndMinDto = findMaxAndMinWithLimit(limit).apply(values);
  66. System.out.println(maxAndMinDto);
  67. }
  68. }
Success #stdin #stdout 4.77s 117260KB
stdin
Standard input is empty
stdout
MaxAndMinDto{max=[2147482948, 2147482144, 2147480305, 2147479108, 2147477375], min=[-2147481687, -2147479985, -2147479343, -2147479227, -2147477344]}