在Java中将列表转换为集的最简单的方法是什么?
当前回答
如果使用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的提交者
其他回答
Set<Foo> foo = new HashSet<Foo>(myList);
我同意sepp2k,但还有其他一些细节可能很重要:
new HashSet<Foo>(myList);
会给你一个没有重复项的无序集合。在这种情况下,使用对象上的.equals()方法标识复制。这是与. hashcode()方法一起完成的。(更多关于平等的信息请点击这里)
给出一个排序集合的替代方法是:
new TreeSet<Foo>(myList);
如果Foo实现Comparable,这是有效的。如果没有,你可以使用比较器:
Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
这取决于compareTo()(来自可比较接口)或compare()(来自比较器)来确保唯一性。如果你只关心唯一性,使用HashSet。如果您正在进行排序,那么请考虑TreeSet。(记住:以后再优化!)如果时间效率很重要,则使用HashSet;如果空间效率很重要,则查看TreeSet。注意,Set和Map的更有效实现可以通过Trove(和其他位置)获得。
有多种方法来获取一个Set为:
List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);
// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList); //needs null-check if sourceList can be null.
// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);
// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);
当我们使用collections . toset()时,它返回一个集合,并且根据文档:对于返回的set的类型、可变性、可序列化性或线程安全性没有保证。如果我们想要获得一个HashSet,那么我们可以使用另一种方法来获得一个set(检查set3)。
对于Java 8来说非常简单:
List < UserEntity > vList= new ArrayList<>();
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());
如果你使用Guava库:
Set<Foo> set = Sets.newHashSet(list);
或者,更好:
Set<Foo> set = ImmutableSet.copyOf(list);
推荐文章
- 在流中使用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