使用番石榴将列表转换并转换为Set [英] Transform and convert a List to Set with Guava

查看:73
本文介绍了使用番石榴将列表转换并转换为Set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来转换转换要使用番石榴设置的列表?

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

d喜欢使用方法:

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

这是我的代码,带有 tempCollection

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 );


推荐答案

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

这将创建一个不接受null的ImmutableSet。因此,如果要让Set包含null,则必须使用另一种解决方案,例如当前正在使用的解决方案。

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.

这篇关于使用番石榴将列表转换并转换为Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆