Skip to content

Instantly share code, notes, and snippets.

@amaembo
Last active November 21, 2015 07:02
Show Gist options
  • Save amaembo/eededf7d3038d67cf67c to your computer and use it in GitHub Desktop.
Save amaembo/eededf7d3038d67cf67c to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;
import one.util.streamex.IntStreamEx;
import one.util.streamex.MoreCollectors;
public class FlatMapTest {
public static void main(String[] args) {
List<List<String>> lists = Arrays.asList(Arrays.asList("A", "B", "C"),
Arrays.asList("D", "E", "F", "G"), Arrays.asList("H", "I"),
Collections.nCopies(5, "J"));
System.out.println("Indices are "
+ Arrays.toString(indices(lists, "J")));
System.out.println("---");
System.out.println("Indices are "
+ Arrays.toString(indicesEx(lists, "J")));
}
public static int[] indices(List<? extends List<?>> lists, Object o) {
return IntStream
.range(0, lists.size())
.boxed()
.<int[]> flatMap(
i -> IntStream.range(0, lists.get(i).size()).mapToObj(
j -> new int[] { i, j })).parallel()
.filter(a -> {
System.out.println(Arrays.toString(a)); // For testing only
return Objects.equals(o, lists.get(a[0]).get(a[1]));
}).findAny().orElse(null);
}
public static int[] indicesEx(List<? extends List<?>> lists, Object o) {
return IntStreamEx
.range(0, lists.size())
.boxed()
.<int[]> flatMap(
i -> IntStream.range(0, lists.get(i).size()).mapToObj(
j -> new int[] { i, j })).parallel()
.filter(a -> {
System.out.println(Arrays.toString(a)); // For testing only
return Objects.equals(o, lists.get(a[0]).get(a[1]));
}).unordered().collect(MoreCollectors.first()).orElse(null);
}
}
[0, 0]
[0, 1]
[0, 2]
[2, 0]
[2, 1]
[3, 0]
[3, 1]
[3, 2]
[3, 3]
[3, 4]
[1, 0]
[1, 1]
[1, 2]
[1, 3]
Indices are [3, 0]
---
[1, 0]
[0, 0]
[0, 1]
[0, 2]
[2, 0]
[3, 0]
[2, 1]
[1, 1]
[1, 2]
[1, 3]
Indices are [3, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment