1.利用递归进行取出数据:
public static <T> List<List<T>> combinations(List<T> list, int k) {
if (k == 0 || list.isEmpty()) {
return Collections.emptyList();
}
if (k == 1) {
return list.stream().map(e -> Stream.of(e).collect(toList())).collect(toList());
}
Map<Boolean, List<T>> headAndTail = split(list, 1);
List<T> head = headAndTail.get(true);
List<T> tail = headAndTail.get(false);
List<List<T>> c1 = combinations(tail, (k - 1)).stream().map(e -> {
List<T> l = new ArrayList<>();
l.addAll(head);
l.addAll(e);
return l;
}).collect(Collectors.toList());
List<List<T>> c2 = combinations(tail, k);
c1.addAll(c2);
return c1;
}
public static <T> Map<Boolean, List<T>> split(List<T> list, int n) {
return IntStream
.range(0, list.size())
.mapToObj(i -> new SimpleEntry<>(i, list.get(i)))
.collect(partitioningBy(entry -> entry.getKey() < n, mapping(SimpleEntry::getValue, toList())));
}
2.测试用例如下:
@Test
public void shouldFindAllCombinationsOfSize2FromAListWithSize3() throws Exception {
List<String> input = Stream.of("a", "b", "c").collect(toList());
List<List<String>> combinations = P26.combinations(input, 2);
System.out.println("2-->"+combinations.toString());
assertThat(combinations, hasSize(3));
}
3.测试结果如下:
2-->[[a, b], [a, c], [b, c]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)