简体   繁体   中英

Generalized way to generate combinations in Java-8

In a coding exam I stumbled upon a question where I had to perform some operation on combinations of 5 Integers.

I solved it by dynamic programming, the solution was Ok and got accepted.

After coming to Home I started thinking is there any way I can generate these combinations using stream.

Well, I thought for a while and for 2 strings I was able to generate the combinations using flatmap .

List<String> list = Arrays.asList("A", "B");
List<String> combinations =
        list.stream()
                .flatMap(str1 -> list.stream().map(str2 -> str1 + str2))
                .collect(toList());
System.out.println(combinations);

Output as Expected:

[AA, AB, BA, BB]

I am wondering is there any way to generate combinations for Arrays.asList("A", "B","C"); , Arrays.asList("A", "B","C","D",E); by controlling the number of time stream will repeat?

When I generate SET{A/C to mathematics} for Arrays.asList("A", "B","C","D",E); I should get [A],[B],[C],[D]…..,[A,B]…,[A,B,C]….[A,B,C,D].

I want a generalized way by which one can get set of elements consisting one element, set consisting two elements...and so on. __________________________________________________________________________-

Apart from the above doubt, I want to know that while generating the set with flatmap inside flatmap I am able to get AA , BB , AB , BA , while it contradicts the basic mathematical definition of set , In mathematics AB or BA are just one set. How to overcome this ?

Don't think that it's a good idea to jam everything you can into streams. There's nothing wrong with loops and recursion.

That said, if you really want to, you can do it like this:

    List<String> list = Arrays.asList("A", "B", "C");
    List<String> combinations = list.stream()
        .reduce(Collections.<String>emptyList(),
            (sets, item) -> {
                return Stream.of(
                    sets.stream(),
                    Stream.of(item),
                    sets.stream().map(str->str+item)
                ).flatMap(x->x).collect(Collectors.toList());
            },
            (sets, sets2) -> { 
                throw new UnsupportedOperationException(
                    "Impossible error in sequential streams");
            }
        );
    System.out.println(combinations);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM