在Java中将列表转换为集的最简单的方法是什么?
当前回答
Set<Foo> foo = new HashSet<Foo>(myList);
其他回答
请记住,从List转换到Set将从集合中删除重复项,因为List支持重复项,而Set在Java中不支持重复项。
直接转换:将List转换为Set的最常见和最简单的方法
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting a list to set
Set<String> set = new HashSet<>(list);
Apache Commons Collections:你也可以使用Commons Collections API将一个List转换为一个Set
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Creating a set with the same number of members in the list
Set<String> set = new HashSet<>(4);
// Adds all of the elements in the list to the target set
CollectionUtils.addAll(set, list);
使用流:另一种方法是将给定的列表转换为流,然后将流转换为集:-
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting to set using stream
Set<String> set = list.stream().collect(Collectors.toSet());
如果使用Eclipse Collections:
MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();
MutableIntSet接口扩展了java.util.Set,而MutableIntSet接口没有。您还可以使用Sets工厂类将任何Iterable转换为Set。
Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));
在Eclipse Collections中有更多关于可变工厂的解释。
如果你想从List中获得一个ImmutableSet,你可以像下面这样使用Sets工厂:
ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))
注意:我是Eclipse Collections的提交者
对于Java 8来说非常简单:
List < UserEntity > vList= new ArrayList<>();
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());
可以将List<>转换为Set<>
Set<T> set=new HashSet<T>();
//Added dependency -> If list is null then it will throw NullPointerExcetion.
Set<T> set;
if(list != null){
set = new HashSet<T>(list);
}
我将在转换为set之前执行Null检查。
if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 如何检查IEnumerable是否为空或空?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder