在Java中将列表转换为集的最简单的方法是什么?
当前回答
使用构造函数的最好方法
Set s= new HashSet(list);
在java 8中,你也可以使用stream api::
Set s= list.stream().collect(Collectors.toSet());
其他回答
使用java 8你可以使用stream:
List<Integer> mylist = Arrays.asList(100, 101, 102);
Set<Integer> myset = mylist.stream().collect(Collectors.toSet()));
请记住,从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());
使用构造函数的最好方法
Set s= new HashSet(list);
在java 8中,你也可以使用stream api::
Set s= list.stream().collect(Collectors.toSet());
在Java 10中,您现在可以使用Set#copyOf轻松地将List<E>转换为不可修改的Set<E>:
例子:
var set = Set.copyOf(list);
请记住,这是一个无序操作,不允许使用空元素,因为它将抛出NullPointerException异常。
如果您希望它是可修改的,那么只需将它传递给构造函数一个Set实现。
如果使用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的提交者
推荐文章
- 使用Jackson将JSON字符串转换为漂亮的打印JSON输出
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- Javadoc @see或{@link}?
- 在准备语句中使用“like”通配符
- Android Eclipse -无法找到*.apk
- javac和Eclipse编译器之间的区别是什么?
- 工厂模式和策略模式之间的区别是什么?
- 在Java中使用正则表达式提取值
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式