Java 中 array 转 set 什么写法比较好?

2020-12-13 15:50:16 +08:00
 gzk329
Set<Integer> set = Stream.of(Arrays.stream(nums).boxed().parallel().toArray(Integer[]::new)).collect(Collectors.toSet());//nums 为 int 数组

使用并行流是这样嘛?

Set<Integer> set = new HashSet<>(Arrays.asList(nums)); 或者这种写法的问题在哪儿 set 没有针对 list 的构造函数? 求指教

3115 次点击
所在节点    Java
13 条回复
ztcaoll222
2020-12-13 15:54:59 +08:00
Set.of(someArray);
chenset
2020-12-13 16:18:48 +08:00
haha ..
weixiaoyun
2020-12-13 17:02:38 +08:00
guava Sets.newHashSet(nums)
gzk329
2020-12-13 17:06:27 +08:00
额 做算法题的时候用 不导入别的 就 jdk
gzk329
2020-12-13 17:14:08 +08:00
/**
226 * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin
227 * convenience for creating an empty set and then calling {@link Iterators#addAll}.
228 *
229 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link
230 * ImmutableSet#copyOf(Iterator)} instead.
231 *
232 * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an {@link EnumSet}
233 * instead.
234 *
235 * <p>Overall, this method is not very useful and will likely be deprecated in the future.
236 */
237 public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
238 HashSet<E> set = newHashSet();
239 Iterators.addAll(set, elements);
240 return set;
241 }
yazinnnn
2020-12-13 17:35:17 +08:00
引入 kotlin 库
java 写法
ArraysKt.toSet(arr)

kotlin 写法
arr.toSet()
或者
setOf(*arr)
xgfan
2020-12-13 17:47:21 +08:00
算法题里用……
算法题里就不该用到这种转换。
zxCoder
2020-12-13 21:10:35 +08:00
算法题 forforfor 就好了
cheng6563
2020-12-13 21:31:14 +08:00
并行装个箱这有啥好并的
gzk329
2020-12-14 08:47:47 +08:00
@zxCoder
@xgfan 主要是前天做的题目 本来是直接模拟的 forfor 用了 o(N2)时间复杂度 然后就有 3 个数据量大的测试例子超时
后来想的是 map 简化 结果还是超时,再后来想的是用 set 先把数组去重,这个 array 转 set 就一直写不好 直接 for 然后 add 进 set 的话肯定超时,后来大概也知道我这个思路是有问题 但是又想把这个思路写出来 就在找直接转的 api,这种做法时间复杂度应该得小于 o(N)
zxCoder
2020-12-14 08:50:47 +08:00
@gzk329 算法复杂度不是这样算的吧。。。。如果你 for add 进也超时,那无论用什么 api 转 复杂度也是不对的
gzk329
2020-12-14 08:58:56 +08:00
@zxCoder 对的啊 就是想通了 所以不找了
samin
2020-12-25 10:28:06 +08:00
我的学习笔记里面有 array to list, 采用你这种做法
https://github.com/SaminZou/study-prj

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/734984

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX