代码之家  ›  专栏  ›  技术社区  ›  user4202236

java中的拆分集

  •  0
  • user4202236  · 技术社区  · 1 年前

    我正试图找到用java保留一个集合的前半部分的最佳方法。 我的Set(java.util.Set)包含60000个元素,我只需要保留其中的前30000个。

    做这件事最好的方法是什么?

    2 回复  |  直到 1 年前
        1
  •  0
  •   StackFlowed    1 年前

    使用Guava库,我们可以使用Lists.partition()方法将列表拆分为连续的子列表,每个列表指定大小

    Java文档:

    https://guava.dev/releases/21.0/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-

    您也可以使用

    https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true#subList-int-int-

    专门用于设置

    Set<Integer> subset = ImmutableSet.copyOf(Iterables.limit(set, 30000)); 
    

    Guava医生:

    https://guava.dev/releases/21.0/api/docs/com/google/common/collect/Iterables.html#limit-java.lang.Iterable-int-

    用户流:

    yourSet.stream().limit(30000).collect(Collectors.toSet());
    
        2
  •  0
  •   Abdullah Al Mamun    1 年前

    Java的Set接口中没有直接的方法来切片或保留组件的特定部分。如果要保留集合中的前30000个元素,可以将集合转换为列表,对保留的成员执行所需操作,然后从保留的元素构建新集合。

    // Your original set with 60,000 elements
    Set<YourElementType> originalSet = new HashSet<>();
    
    // Convert the Set to a List
    List<YourElementType> originalList = new ArrayList<>(originalSet);
    
    // Retain the first 30,000 elements
    List<YourElementType> retainedList = originalList.subList(0, 30000);
    
    // Create a new Set from the retained elements
    Set<YourElementType> retainedSet = new HashSet<>(retainedList);