Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
val busIdsOnTheRouteStart = IntStream.range(0, 15);
val busIdsOnTheRouteEnd = IntStream.range(16, 30);
val busIdsInboundToggleTuples = busIdsOnTheRouteStart.boxed()
.collect(toMap(identity(), id -> Toggle.from(Direction.INBOUND, Direction.OUTBOUD)));
val busIdsOutboundToggleTuples = busIdsOnTheRouteStart.boxed()
.collect(toMap(identity(), id -> Toggle.from(Direction.OUTBOUD, Direction.INBOUND)));
val busIdDirectionToggleTuples = new HashMap<Integer, Toggle<Direction>>();
busIdDirectionToggleTuples.putAll(busIdsInboundToggleTuples);
busIdDirectionToggleTuples.putAll(busIdsOutboundToggleTuples);
val generatedTrips = new ArrayList<Trip>();
busIdDirectionToggleTuples.forEach((busId, directionToggle) -> {
generatedTrips.add(genTrip(busId, directionToggle.get(), ...));
directionToggle.toggle();
});
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.IntStream;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.val;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.apache.commons.lang3.Validate.notNull;
@ToString
@EqualsAndHashCode
public class Toggle<T> {
private final T baseValue;
private final T toggledValue;
private T currentValue;
public Toggle(T baseValue, T toggledValue) {
this.baseValue = notNull(baseValue);
this.toggledValue = notNull(toggledValue);
this.currentValue = baseValue;
}
public static <T> Toggle<T> from(T baseValue, T toggledValue) {
return new Toggle<>(baseValue, toggledValue);
}
public T get() {
return currentValue;
}
public T getAndToggle() {
val currVal = get();
toggle();
return currVal;
}
public T toggleAndGet() {
toggle();
return get();
}
public void toggle() {
currentValue = (currentValue == baseValue) ? toggledValue : baseValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment