Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform and convert a List to Set with Guava

Is there a simple way to convert and transform a List to Set with Guava?

I'd like to use method:

Set<To> result = Sets.transformToSet(myList, new Function<From, To>() {
            public To apply(From item) {
                return convert(item);
            }
        });

this is my code, with "tempCollection"

Collection<To> tempCollection = Collections2.transform(myList, new Function<From, To>() {
            public To apply(From item) {
                return convert(item);
            }
        });
Set<To> result = newHashSet(tempCollection );
like image 410
Omar Hrynkiewicz Avatar asked Nov 19 '13 19:11

Omar Hrynkiewicz


1 Answers

Set<To> result = FluentIterable.from(myList)
                               .transform(new Function<From, To>() {
                                   @Override
                                   public To apply(From input) {
                                       return convert(input);
                                   }
                               })
                               .toSet();

This creates an ImmutableSet, which does not accept null. So if you want your Set to contain null, you'll have to use another solution, like the one you're currently using.

Note that, if it's the creation of the temporary collection that bothers you, you shouldn't be bothered. No copy is made. The collection is simply a view over the original list.

like image 124
JB Nizet Avatar answered Oct 04 '22 18:10

JB Nizet