Java Stream 排列组合
使用 Java Stream 实现排列组合
1 package org.htsg.utils; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.List; 6 import java.util.stream.Collectors; 7 import java.util.stream.IntStream; 8 import java.util.stream.Stream; 9 10 /** 11 * @author HTSG 12 */ 13 14 /** 15 * 获取数组元素的全组合 16 * 17 * @param sources 源数组 18 * @param <E> 类型 19 * @return 全组合 20 */ 21 public static <E> List<List<E>> combination(E[] sources) { 22 return IntStream.range(1, 1 << sources.length) 23 .parallel() 24 .mapToObj(i -> IntStream.range(0, sources.length) 25 .filter(j -> (i & (1 << j)) != 0) 26 .mapToObj(j -> sources[j]) 27 .collect(Collectors.toList())) 28 .collect(Collectors.toList()); 29 } 30 31 public static <E> List<List<E>> combination(List<E> sources) { 32 return IntStream.range(1, 1 << sources.size()) 33 .parallel() 34 .mapToObj(i -> IntStream.range(0, sources.size()) 35 .filter(j -> (i & (1 << j)) != 0) 36 .mapToObj(sources::get) 37 .collect(Collectors.toList())) 38 .collect(Collectors.toList()); 39 } 40 41 /** 42 * 获取数组元素的全排列 43 * 44 * @param sources 源数组 45 * @param <E> 类型 46 * @return 全排列 47 */ 48 public static <E> List<List<E>> fullPermutationBySelf(E[] sources) { 49 return fullPermutationBySelf(Arrays.asList(sources)); 50 } 51 52 public static <E> List<List<E>> fullPermutationBySelf(List<E> sources) { 53 Stream<List<E>> stream = sources.parallelStream().map(Arrays::asList); 54 for (int i = 1; i < sources.size(); i++) { 55 stream = stream 56 .flatMap(l -> 57 sources.stream() 58 .filter(e -> !l.contains(e)) 59 .map(e -> { 60 ArrayList<E> temp = new ArrayList<>(l); 61 temp.add(e); 62 return temp; 63 })); 64 } 65 return stream.collect(Collectors.toList()); 66 } 67 68 /** 69 * 获取数组元素的排列 70 * 71 * @param sources 源数组 72 * @param <E> 类型 73 * @return 排列 74 */ 75 public static <E> List<List<E>> permutationBySelf(E[] sources) { 76 return permutationBySelf(Arrays.asList(sources)); 77 } 78 79 public static <E> List<List<E>> permutationBySelf(List<E> sources) { 80 Stream<List<E>> stream = sources.parallelStream().map(Arrays::asList); 81 for (int i = 1; i < sources.size(); i++) { 82 stream = stream 83 .flatMap(l -> 84 sources.stream() 85 .map(e -> { 86 ArrayList<E> temp = new ArrayList<>(l); 87 temp.add(e); 88 return temp; 89 })); 90 } 91 return stream.collect(Collectors.toList()); 92 } 93 94 public static <E> List<List<E>> permutation(List<List<E>> sources) { 95 Stream<List<E>> stream = sources.get(0).stream().map(Arrays::asList); 96 for (int i = 1; i < sources.size(); i++) { 97 final int index = i; 98 stream = stream.flatMap(l -> sources.get(index).stream() 99 .map(e -> { 100 ArrayList<E> temp = new ArrayList<>(l); 101 temp.add(e); 102 return temp; 103 })); 104 } 105 return stream.collect(Collectors.toList()); 106 }
浙公网安备 33010602011771号