Last active
February 26, 2017 11:19
-
-
Save calumleslie/8fe772225b8403e515286a56b965b985 to your computer and use it in GitHub Desktop.
"No one used Java 8." -- https://shekhargulati.com/2017/02/24/why-its-hard-for-programmers-to-write-a-program-to-flatten-a-list/
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
package flatten; | |
import java.util.Arrays; | |
import java.util.Optional; | |
import java.util.OptionalInt; | |
import java.util.function.Function; | |
import java.util.function.IntFunction; | |
import java.util.stream.IntStream; | |
public class ArrayOrInt { | |
private final Optional<ArrayOrInt[]> array; | |
private final OptionalInt integer; | |
public ArrayOrInt(Optional<ArrayOrInt[]> array, OptionalInt integer) { | |
if (!(array.isPresent() ^ integer.isPresent())) { | |
throw new IllegalArgumentException(); | |
} | |
this.array = array; | |
this.integer = integer; | |
} | |
public static ArrayOrInt of(int value) { | |
return new ArrayOrInt(Optional.empty(), OptionalInt.of(value)); | |
} | |
public static ArrayOrInt of(int... values) { | |
ArrayOrInt[] objects = IntStream.of(values).mapToObj(ArrayOrInt::of).toArray(ArrayOrInt[]::new); | |
return ArrayOrInt.of(objects); | |
} | |
public static ArrayOrInt of(ArrayOrInt... values) { | |
return new ArrayOrInt(Optional.of(values), OptionalInt.empty()); | |
} | |
public <T> T map(Function<ArrayOrInt[], T> ifArray, IntFunction<T> ifInt) { | |
return array.map(ifArray).orElseGet(() -> ifInt.apply(integer.getAsInt())); | |
} | |
@Override | |
public String toString() { | |
return map(Arrays::toString, Integer::toString); | |
} | |
} |
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
package flatten; | |
import static flatten.ArrayOrInt.of; | |
import java.util.Arrays; | |
import java.util.stream.IntStream; | |
import java.util.stream.Stream; | |
public class Flatten { | |
public static void main(String[] args) { | |
ArrayOrInt input = of(of(1), of(2, 3), of(of(4), of(5, 6))); | |
System.out.println(input); | |
// [1, [2, 3], [4, [5, 6]]] | |
int[] flattened = flatten(input).toArray(); | |
System.out.println(Arrays.toString(flattened)); | |
// [1, 2, 3, 4, 5, 6] | |
} | |
private static IntStream flatten(ArrayOrInt in) { | |
return in.map(items -> Stream.of(items).flatMapToInt(Flatten::flatten), IntStream::of); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment