Java 使用 Guava 将 List 转换和转换为 Set

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20080635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:58:06  来源:igfitidea点击:

Transform and convert a List to Set with Guava

javacollectionsguava

提问by Omar Hrynkiewicz

Is there a simple way to convertand transforma List to Set with Guava?

有没有一种简单的方法可以使用 Guava 将 List转换转换为 Set?

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"

这是我的代码,带有“tempCollection”

Collection<To> tempCollection = Collections2.transform(myList, new Function<From, To>() {
            public To apply(From item) {
                return convert(item);
            }
        });
Set<To> result = newHashSet(tempCollection );

采纳答案by JB Nizet

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.

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

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.

请注意,如果困扰您的是临时集合的创建,您不应该被打扰。没有复制。该集合只是原始列表的视图。