Combine different list in to Set(single list) in Java 8 using Stream API

Combine the different list in to single list in java, there should be used in java 8 Creating a stream pipeline that transforms a list of sets (of type String) into the union of those
sets. Make use of the reduce method for streams.
Example:
Orginal list [{“A”, “B”}, {“D”}, {“1”, “3”, “5”}] to the
Final Set
{“A”, “B”, “D”, “1”, “3”, “5”}.

Code looks like:
public class Union {

    public static void main(String[] args) {
        List<Set<String>> list = new ArrayList<>();
        Set<String> set1 = new LinkedHashSet<>(Arrays.asList(new String[]{"A", "B"}));
        list.add(set1);

        Set<String> set2 = new LinkedHashSet<>(Arrays.asList(new String[]{"D"}));
        list.add(set2);

        Set<String> set3 = new LinkedHashSet<>(Arrays.asList(new String[]{"1", "2", "3"}));
        list.add(set3);

        System.out.println("input: " + list);

        System.out.println("output:" + combinedList(list));

    }

    public static Set<String> combinedList(List<Set<String>> sets) {
        Optional<Set<String>> stream = sets.stream().reduce((t, u) -> {
            t.addAll(u);
            return t;
        });

        return stream.get();
    }
}



Happy Coding !!!

0 comments:

Post a Comment