Skip to content

Instantly share code, notes, and snippets.

@JosePaumard
Created January 12, 2015 16:07
Show Gist options
  • Save JosePaumard/424051ad3280e03e9b18 to your computer and use it in GitHub Desktop.
Save JosePaumard/424051ad3280e03e9b18 to your computer and use it in GitHub Desktop.
package org.paumard.combination;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Combination {
public static void main(String... args) {
String [] tab1 = {"A", "B", "C", "D" };
String [] tab2 = {"A", "D" };
String [] tab3 = {"A", "B" };
String [] tab4 = {"C", "D" };
String [] tab5 = {"B", "C", "D" };
String [] tab6 = {"B", "A"};
List<String[]> tabs = Arrays.asList(
tab1, tab2, tab3, tab4, tab5, tab6);
tabs.stream()
.map(
tab ->
Stream.of(tab)
.map(
e1 ->
Stream.of(tab)
.filter(e2 -> e1.compareTo(e2) < 0)
.map(
e2 -> Pair.of(e1, e2)
)
)
.flatMap(Function.identity())
)
.flatMap(Function.identity())
.collect(
Collectors.groupingBy(
Function.identity(),
Collectors.counting()
)
)
.entrySet()
.stream()
// a bug in the compiler prevents from using
// Map.Entry.comparingByValue().reversed()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);
}
static class Pair {
String a, b ;
static Pair of(String a, String b) {
Pair p = new Pair() ;
p.a = a ;
p.b = b ;
return p ;
}
@Override
public String toString() {
return "[" + a + ", " + b + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (b == null) {
if (other.b != null)
return false;
} else if (!b.equals(other.b))
return false;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment