Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create immutable set from another immutable set?

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!

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading