포스트

자바) combination/ stream

자바) combination/ stream

이 글은 Tistory에서 이전된 포스팅입니다. 원본은 여기에서 확인할 수 있습니다.

combination

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    static List<List<Integer>> combination(List<Integer> list, List<Integer> result, int depth) {
        List<List<Integer>> r = new ArrayList<>();
        if (result.size() == depth) {
            r.add(result);
            return r;
        }
        for (int i = 0; i < list.size(); i++) {
            List<Integer> n_list = new ArrayList<>(list.stream().skip(i + 1).collect(Collectors.toList()));
            List<Integer> n_result = new ArrayList<>(result.stream().collect(Collectors.toList()));
            n_result.add(list.get(i));
            List<List<Integer>> rr = combination(n_list, n_result, depth);
            for (List<Integer> rrr : rr) {
                r.add(rrr);
            }
        }
        return r;
    }

list slice 복사 : list.stream().skip(i + 1).collect(Collectors.toList());
앞에서부터 skip 개수만큼 건너뛴다. 마지막 변환을 stream().toList() 로 가능한데 8은 안됨으로 Collectors 사용

add가능한 list를 위해 new ArrayList<>() 로 만든다.

int[] -> Integer[]

1
Integer[] n_nums = Arrays.stream(nums).boxed().toArray(Integer[]::new);

위 코드는 기존에 posting한 적 있지만 기억하자는 의미로

list sum

1
int sum = rr.stream().mapToInt(Integer::intValue).sum();
이 기사는 저작권자의 CC BY-NC 4.0 라이센스를 따릅니다.