[英]Convert a Linked List of type Integer to Set of type String in JAVA
我有一个Integers
List
,但我想获取该List
并将其转换为HashSet
。
例如,我的列表如下:
1234
5678
1234
7627
4328
但是我想获取该list
并将整数字符串转换为HashSet
以便它不包括重复项。 做到这一点的最佳方法是什么?
我的list
定义为
static List<Integer> list;
我的HashSet
定义为
static HashSet<String> set = new HashSet<String>(list);
我的错误是我无法从int转换为string,所以我该怎么办呢?
一种方法是使用流:
Set<String> set = list.stream()
.map(Object::toString)
.collect(Collectors.toSet());
首先,您流式传输列表。 然后,将每个元素转换为字符串,最后将所有元素收集到一个集合中。 默认情况下, Collectors.toSet()
创建一个HashSet
,尽管规范没有保证。
如果您想要一个有保证的HashSet
,则可以使用Collectors.toCollection(HashSet::new)
:
Set<String> set = list.stream()
.map(Object::toString)
.collect(Collectors.toCollection(HashSet::new));
使用Java 8流:
set = list.stream().map(e -> e.toString()).collect(Collectors.toCollection(HashSet::new));
或不使用流
for(Integer i : list) set.add(Integer.toString(i));
假设您使用ArrayList作为List <>的实例化形式:
for (Integer value : list) {
set.add(value.toString());
}
这将遍历List并获取每个整数,将其转换为String,然后将该值添加到HashSet中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.