Skip to content

Instantly share code, notes, and snippets.

@jaycobbcruz
Created April 30, 2017 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaycobbcruz/893f279a329663751173cca8d039d142 to your computer and use it in GitHub Desktop.
Save jaycobbcruz/893f279a329663751173cca8d039d142 to your computer and use it in GitHub Desktop.
Create pairs/combinations of items
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