简体   繁体   English

如何从 Java 中的集合中删除特定元素

[英]How to remove specific element from collection in Java

I have declared a specific collecion looking like this我已经宣布了一个看起来像这样的特定集合

private static String[] testCollection= new String[]
        {"DB085175AF684343888344561C2723C1",
         "DB085175AF684343888344561C2723C2"}

Then there is a method that returns a random element from my collection.然后有一种方法可以从我的集合中返回一个随机元素。

public static <T> T getRandomElement(Collection<T> collection)
{
    int size = collection.size();
    return (T) collection.toArray()[random.nextInt(size)];
}

So my question is how to remove randomly chosen element when i declare it like所以我的问题是当我声明它时如何删除随机选择的元素

String testName = CollectionUtil.getRandomElement(informationSystemName);

I can't figure out how to build a method that removes generated testName from testCollection我不知道如何构建一个从testCollection中删除生成的testName的方法

Arrays in Java have a fixed size, which is set when the array is created. Java 中的 Arrays 有一个固定的大小,在创建数组时设置。 You cannot remove an element from an existing array such as testCollection - you'll have to create a new array without the element that you want to remove.您不能从现有数组(例如testCollection )中删除元素 - 您必须创建一个没有要删除的元素的新数组。

This is easier if you first convert the array to a List , use the remove() method of List to remove the desired element, and then create a new array from the list with the element removed:如果您首先将数组转换为List ,使用Listremove()方法删除所需元素,然后从列表中创建一个删除元素的新数组,这会更容易:

List<String> list = new ArrayList<>(Arrays.asList(testCollection));
list.remove(testName);
    
String[] result = list.toArray(new String[list.size()]);

Or work with List directly instead of arrays - collection classes such as List are more flexible and often more useful than arrays:或者直接使用List而不是 arrays - List等集合类比 arrays 更灵活且通常更有用:

private static List<String> testCollection = List.of(
    "DB085175AF684343888344561C2723C1", "DB085175AF684343888344561C2723C2");

public static <T> T getRandomElement(List<T> collection) {
    int size = collection.size();
    return collection.get(random.nextInt(size));
}

String testName = getRandomElement(testCollection);
testCollection.remove(testName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM