Created
February 11, 2017 15:26
-
-
Save amaembo/bb65d43ac4202b584ce6c0a29db16aaf to your computer and use it in GitHub Desktop.
An addition to http://stackoverflow.com/a/42176321/4856258 (using StreamEx)
This file contains hidden or 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
import one.util.streamex.EntryStream; | |
import one.util.streamex.StreamEx; | |
import java.util.*; | |
public class Test { | |
static List<List<Integer>> mergeCollections(List<List<Integer>> input) { | |
return StreamEx.of(input).foldLeft(Collections.emptyList(), | |
(List<List<Integer>> acc, List<Integer> listInner) -> EntryStream | |
.of(StreamEx.of(acc).partitioningBy(list -> list.stream().anyMatch(listInner::contains))) | |
.mapKeyValue((b, list) -> b ? | |
Collections.singleton(StreamEx.of(list).flatMap(List::stream).append(listInner).distinct().toList()) | |
: list) | |
.flatMap(Collection::stream) | |
.toList()); | |
} | |
public static void main(String[] args) { | |
List<List<Integer>> mainList = new ArrayList<List<Integer>>(); | |
mainList.add(Arrays.asList(0, 1)); | |
mainList.add(Arrays.asList(0, 1, 2)); | |
mainList.add(Arrays.asList(1, 2)); | |
mainList.add(Arrays.asList(3)); | |
System.out.println(mergeCollections(mainList)); | |
mainList = new ArrayList<List<Integer>>(); | |
mainList.add(Arrays.asList(0,2)); | |
mainList.add(Arrays.asList(1,4)); | |
mainList.add(Arrays.asList(0,2,4)); | |
mainList.add(Arrays.asList(3,4)); | |
mainList.add(Arrays.asList(1,3,4)); | |
System.out.println(mergeCollections(mainList)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment