fork download
  1. import java.util.*;
  2. import java.util.stream.*;
  3. import java.util.function.*;
  4.  
  5.  
  6. class Ideone
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10. List<Integer> list = Arrays.asList(4,3,7,1,5,2,9);
  11. System.out.println(list.stream().collect(COLLECT_MIN));
  12. }
  13.  
  14. static Collector<Integer, Minimum, Integer> COLLECT_MIN = new Collector<Integer, Minimum, Integer>() {
  15. @Override
  16. public Supplier<Minimum> supplier() {
  17. return Minimum::new;
  18. }
  19. @Override
  20. public BiConsumer<Minimum, Integer> accumulator() {
  21. return Minimum::accept;
  22. }
  23. @Override
  24. public BinaryOperator<Minimum> combiner() {
  25. return Minimum::combine;
  26. }
  27. @Override
  28. public Function<Minimum, Integer> finisher() {
  29. return Minimum::getIndex;
  30. }
  31. @Override
  32. public Set<Collector.Characteristics> characteristics() {
  33. return Collections.emptySet();
  34. }
  35. };
  36.  
  37. static class Minimum {
  38. int index = -1;
  39. int range = 0;
  40. int value;
  41.  
  42. public void accept(int value) {
  43. if (range == 0 || value < this.value) {
  44. index = range;
  45. this.value = value;
  46. }
  47. range++;
  48. }
  49.  
  50. public Minimum combine(Minimum other) {
  51. if (value > other.value) {
  52. index = range + other.index;
  53. value = other.value;
  54. }
  55. range += other.range;
  56. return this;
  57. }
  58.  
  59. public int getIndex() {
  60. return index;
  61. }
  62. }
  63. }
Success #stdin #stdout 0.19s 320576KB
stdin
Standard input is empty
stdout
3