Created
April 30, 2017 10:18
-
-
Save jaycobbcruz/893f279a329663751173cca8d039d142 to your computer and use it in GitHub Desktop.
Create pairs/combinations of items
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
public class Pairs { | |
/** | |
* Create a list of pairs of the given items. | |
* e.g. ["A", "B", "C", "D"] will return ["A:B", "A:C", "A:D", "B:C", "B:D", "C:D"] | |
* @param items the items to create the pair | |
* @param <T> type of the items | |
* @return a list of pairs | |
*/ | |
public static <T> List<Pair<T, T>> of(final List<T> items) { | |
final List<Pair<T, T>> pairs = new ArrayList<>(); | |
items.forEach((T left) -> items.stream().filter(right -> !left.equals(right) && !pairs.contains(new Pair<>(right, left))) | |
.forEach(right -> pairs.add(new Pair<>(left, right)))); | |
return pairs; | |
} | |
/** | |
* Create a group of pairs of the given items, group by the pair's left. | |
* e.g. ["A", "B", "C", "D"] will return [A=>[A:B,A:C,A:D], B=>[B:C,B:D], [C=>C:D]] | |
* @param items the items to create the pair and grouped | |
* @return the grouped pairs | |
*/ | |
public static <T> Map<String, List<Pair<T, T>>> groupLeft(final List<T> items) { | |
return of(items).stream().collect( groupingBy(Pair::leftString) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment