Home > Mobile >  How to create immutable set from another immutable set?
How to create immutable set from another immutable set?

Time:11-17

Given a set Set<String> s = Set.of("a", "b", "c"), how do I create a new immutable set with the contents of s and some additional data? I tried Set t = Set.of(s, "d"), but this gives me mixed types t ==> [[a, b, c], d]. I need [a, b, c, d]. I am not using Guava. thanks!

CodePudding user response:

Try this.

Set<String> s = Set.of("a", "b", "c");
Set<String> t = Stream.of(s, Set.of("d"))
    .flatMap(Set::stream)
    .collect(Collectors.toUnmodifiableSet());
System.out.println(t);

output

[d, c, b, a]

or

Set<String> t = Stream.of(s.stream(), Stream.of("d"))
    .flatMap(Function.identity())
    .collect(Collectors.toUnmodifiableSet());
  • Related