Rearrange List with Equal Objects - Java
List<String> original = Lists.newArrayList("A", "B", "C");
Collection<List<String>> permutations= Collections2.orderedPermutations(original)
gives
[A, B, C]
[A, C, B]
[B, A, C]
[B, C, A]
[C, A, B]
[C, B, A]
Ok, now I have all the possible permutations. But let them say that A and C are equal, their order does not matter when they are next to each other.
Required Result:
[A, C, B] or [C, A, B]
[B, A, C] or [B, C, A]
[A, B, C]
[C, B, A]
So, we tried to use a comparator
Collection<List<String>> permutations= Collections2.orderedPermutations(original, new Comparator<String>() {
@Override
public int compare(final String o1, final String o2) {
if ((o1.equals("A") && o2.equals("C")) || (o2.equals("A") && o1.equals("C"))) {
return 0;
}
return o1.compareTo(o2);
}
});
But this did not give us the expected result.
[A, B, C]
[A, C, B]
Any suggestions on how to get your desired result? Although we used guava, any lib or custom solution is ok.
, , , 3-, , A C :
[A, B, A]
[A, A, B]
[B, A, A]
[B, A, A]
[A, A, B]
[A, B, A]
:
[A, B, A]
[A, A, B]
[B, A, A]
Set<List<String>>, , ..
List<String> original = Lists.newArrayList("A", "B", "C");
Collection<List<String>> permutations = Collections2.orderedPermutations(original);
// now add your collection to a set to remove duplicates
Set<List<String>> permsNoDupes = new HashSet<>(permutations);
My offer is paired ("A", "C") and ("C", "A") always puts "A" first and converts it to ("A", "C")
List<String> original = Lists.newArrayList("A", "B", "C");
Set<List<String>> permutations = Collections2.orderedPermutations(original).
stream().
map(list -> {
int indexOfc = list.get(0) == "C" ? 0 : (list.get(1) == "C" ? 1 : -1);
if (indexOfc != -1 && list.get(indexOfc + 1) == "A") {
// modifications not allowed on original list
list = new ArrayList<>(list);
list.set(indexOfc, "A");
list.set(indexOfc + 1, "C");
}
return list;
}).collect(Collectors.toSet());
results
[[A, B, C], [C, B, A], [B, A, C], [A, C, B]]