Commit 87363416 authored by earndt's avatar earndt

[W6D4] (ArndtED) Adds classes

parent 0f6a3ee3
package com.nisum;
//all credit to https://stackoverflow.com/users/2229438/grzegorz-piwowarek
//https://stackoverflow.com/questions/45981964/how-to-get-a-random-element-from-a-list-with-stream-api/45982130
import java.util.List;
import java.util.Random;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class ImprovedRandomSpliterator<T> implements Spliterator<T> {
private final Random random;
private final T[] source;
private int size;
ImprovedRandomSpliterator(List<T> source, Supplier<? extends Random> random) {
if (source.isEmpty()) {
throw new IllegalArgumentException("RandomSpliterator can't be initialized with an empty collection");
}
this.source = (T[]) source.toArray();
this.random = random.get();
this.size = this.source.length;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
if (size > 0) {
int nextIdx = random.nextInt(size);
int lastIdx = size - 1;
action.accept(source[nextIdx]);
source[nextIdx] = source[lastIdx];
source[lastIdx] = null; // let object be GCed
size--;
return true;
} else {
return false;
}
}
@Override
public Spliterator<T> trySplit() {
return null;
}
@Override
public long estimateSize() {
return source.length;
}
@Override
public int characteristics() {
return SIZED;
}
}
package com.nisum;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.util.stream.Collectors.toCollection;
public class WhoIsTheBest {
private List<String> theGreats;
private List<String> theNotSoGreats;
public WhoIsTheBest(){
this.theGreats = Arrays.asList("Alex P", "Alex S", "Ben", "Chef", "Chris", "Darrick",
"Deep", "Joe", "John", "Julius", "Kevin", "Khai", "Kyle",
"Nikitha", "Philippe", "Shanelle", "Sumaiyya", "Vishal");
this.theNotSoGreats = Arrays.asList("Eric");
}
public List<String> getTheGreats() {
return theGreats;
}
public List<String> getTheNotSoGreats() {
return theNotSoGreats;
}
public Optional<String> gimmeAGreat(){
return theGreats.stream().collect(toShuffledStream()).findAny();
}
public Optional<String> gimmeANotSoGreat(){
return theNotSoGreats.stream().findAny();
}
public static <T> Collector<T, ?, Stream<T>> toShuffledStream() {
return Collectors.collectingAndThen(
toCollection(ArrayList::new),
list -> !list.isEmpty()
? StreamSupport.stream(new ImprovedRandomSpliterator<>(list, Random::new), false)
: Stream.empty());
};
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment