Guest User

Untitled

a guest
Apr 20th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. package vahy.collectors;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import java.util.Set;
  8. import java.util.SplittableRandom;
  9. import java.util.function.BiConsumer;
  10. import java.util.function.BinaryOperator;
  11. import java.util.function.Function;
  12. import java.util.function.Supplier;
  13. import java.util.stream.Collector;
  14.  
  15. public class RandomizedMaxCollector<elementType> implements Collector<elementType, List<elementType>, elementType> {
  16.  
  17. private final Comparator<elementType> comparator;
  18. private final SplittableRandom random;
  19.  
  20. public RandomizedMaxCollector(Comparator<elementType> comparator, SplittableRandom random) {
  21. this.comparator = comparator;
  22. this.random = random;
  23. }
  24.  
  25. @Override
  26. public Supplier<List<elementType>> supplier() {
  27. return ArrayList::new;
  28. }
  29.  
  30. @Override
  31. public BiConsumer<List<elementType>, elementType> accumulator() {
  32. return (list, element) -> {
  33. if(list.isEmpty()) {
  34. list.add(element);
  35. }
  36. int compared = comparator.compare(list.get(0), element);
  37. switch (compared) {
  38. case (0):
  39. list.add(element);
  40. break;
  41. case (1):
  42. break; // leaving list as is
  43. case (-1): {
  44. list.clear();
  45. list.add(element);
  46. break;
  47. }
  48. default:
  49. throw new IllegalStateException("Comparator returns [" + compared + "] which is not defined");
  50. }
  51. };
  52. }
  53.  
  54. @Override
  55. public BinaryOperator<List<elementType>> combiner() {
  56. return (firstList, secondList) -> {
  57. if(firstList.isEmpty()) {
  58. return secondList;
  59. }
  60. if(secondList.isEmpty()) {
  61. return firstList;
  62. }
  63. int compared = comparator.compare(firstList.get(0), secondList.get(0));
  64. switch (compared) {
  65. case(0):
  66. firstList.addAll(secondList);
  67. return firstList;
  68. case(1):
  69. return firstList;
  70. case(-1):
  71. return secondList;
  72. default:
  73. throw new IllegalStateException("Comparator returns [" + compared + "] which is not defined");
  74. }
  75. };
  76. }
  77.  
  78. @Override
  79. public Function<List<elementType>, elementType> finisher() {
  80. return list -> list.get(random.nextInt(list.size()));
  81. }
  82.  
  83. @Override
  84. public Set<Characteristics> characteristics() {
  85. return Collections.emptySet();
  86. }
  87. }
Add Comment
Please, Sign In to add comment