Created
April 12, 2018 13:32
-
-
Save snurkabill/a4c059909542ba51ad58aea10ea015b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RandomizedMaxCollector<elementType> implements Collector<elementType, List<elementType>, elementType> { | |
private final Comparator<elementType> comparator; | |
private final SplittableRandom random; | |
public RandomizedMaxCollector(Comparator<elementType> comparator, SplittableRandom random) { | |
this.comparator = comparator; | |
this.random = random; | |
} | |
@Override | |
public Supplier<List<elementType>> supplier() { | |
return ArrayList::new; | |
} | |
@Override | |
public BiConsumer<List<elementType>, elementType> accumulator() { | |
return (list, elementType) -> { | |
int compared = comparator.compare(list.get(0), elementType); | |
switch (compared) { | |
case (0): | |
list.add(elementType); | |
break; | |
case (1): | |
break; // leaving list as is | |
case (-1): { | |
list = supplier().get(); | |
list.add(elementType); | |
break; | |
} | |
default: | |
throw new IllegalStateException("Comparator returns [" + compared + "] which is not defined"); | |
} | |
}; | |
} | |
@Override | |
public BinaryOperator<List<elementType>> combiner() { | |
return (firstList, secondList) -> { | |
int compared = comparator.compare(firstList.get(0), secondList.get(0)); | |
switch (compared) { | |
case(0): | |
firstList.addAll(secondList); | |
return firstList; | |
case(1): | |
return firstList; | |
case(-1): | |
return secondList; | |
default: | |
throw new IllegalStateException("Comparator returns [" + compared + "] which is not defined"); | |
} | |
}; | |
} | |
@Override | |
public Function<List<elementType>, elementType> finisher() { | |
return list -> list.get(random.nextInt(list.size())); | |
} | |
@Override | |
public Set<Characteristics> characteristics() { | |
return Collections.emptySet(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment