Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Permutations from two Sets using Java Streams

I have two Sets - country and state. I want to create all possible permutations from both.

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");

        Set<String> countryPermutations = new HashSet<>(Arrays.asList("United States of america", "USA"));

        Set<String> statePermutations = new HashSet<>(Arrays.asList("Texas", "TX"));

        Set<String> stateCountryPermutationAliases = countryPermutations.stream()
        .flatMap(country -> statePermutations.stream()
        .map(state -> state + country))
        .collect(Collectors.toSet());

        System.out.println(stateCountryPermutationAliases);
     }
    }

This gives the output

[TexasUSA, TXUSA, TXUnited States of america, TexasUnited States of america]

I however want the opposite concatenation as well - country + state. How can I extend my lambda to do this?

like image 716
Pranav Kapoor Avatar asked Sep 10 '26 02:09

Pranav Kapoor


1 Answers

 Set<String> stateCountryPermutationAliases = countryPermutations.stream()
            .flatMap(country -> statePermutations.stream()
                    .flatMap(state -> Stream.of(state + country, country + state)))
            .collect(Collectors.toSet());
like image 182
Eugene Avatar answered Sep 14 '26 21:09

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!