gzk329
V2EX  ›  Java

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

  •  
  •   gzk329 · Dec 13, 2020 · 4096 views
    This topic created in 2163 days ago, the information mentioned may be changed or developed.
    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 的构造函数? 求指教

    13 replies  •  2020-12-25 10:28:06 +08:00
    ztcaoll222
    ztcaoll222
    Dec 13, 2020❤️3
    1
    Set.of(someArray);
    chenset
    chenset
    Dec 13, 2020
    2
    haha ..
    weixiaoyun
    weixiaoyun
    Dec 13, 2020
    3
    guava Sets.newHashSet(nums)
    gzk329
    gzk329
    OP
    Dec 13, 2020
    4
    额 做算法题的时候用 不导入别的 就 jdk
    gzk329
    gzk329
    OP
    Dec 13, 2020
    5
    /**
    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
    yazinnnn
    Dec 13, 2020
    6
    引入 kotlin 库
    java 写法
    ArraysKt.toSet(arr)

    kotlin 写法
    arr.toSet()
    或者
    setOf(*arr)
    6IbA2bj5ip3tK49j
    6IbA2bj5ip3tK49j
    Dec 13, 2020 via iPhone
    7
    算法题里用……
    算法题里就不该用到这种转换。
    zxCoder
    zxCoder
    Dec 13, 2020
    8
    算法题 forforfor 就好了
    cheng6563
    cheng6563
    Dec 13, 2020
    9
    并行装个箱这有啥好并的
    gzk329
    gzk329
    OP
    Dec 14, 2020
    10
    @zxCoder
    @xgfan 主要是前天做的题目 本来是直接模拟的 forfor 用了 o(N2)时间复杂度 然后就有 3 个数据量大的测试例子超时
    后来想的是 map 简化 结果还是超时,再后来想的是用 set 先把数组去重,这个 array 转 set 就一直写不好 直接 for 然后 add 进 set 的话肯定超时,后来大概也知道我这个思路是有问题 但是又想把这个思路写出来 就在找直接转的 api,这种做法时间复杂度应该得小于 o(N)
    zxCoder
    zxCoder
    Dec 14, 2020
    11
    @gzk329 算法复杂度不是这样算的吧。。。。如果你 for add 进也超时,那无论用什么 api 转 复杂度也是不对的
    gzk329
    gzk329
    OP
    Dec 14, 2020
    12
    @zxCoder 对的啊 就是想通了 所以不找了
    samin
    samin
    Dec 25, 2020
    13
    我的学习笔记里面有 array to list, 采用你这种做法
    https://github.com/SaminZou/study-prj
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   891 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 19:58 · PVG 03:58 · LAX 11:58 · JFK 14:58
    ♥ Do have faith in what you're doing.