有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

集合在java中迭代之前删除元素列表

我有一个字符串列表。在满足条件的情况下,我需要对字符串进行分组并在迭代之前删除这些字符串。 比如,

List<String> test = new ArrayList();
List<String> newLst = new ArrayList();
test.add("A1");
test.add("A2");
test.add("A3");
test.add("A1B1");
test.add("C1");
for(String s: test){
    if(s.startsWith("A"){
        newLst.add(s);
        test.remove(s);
    }
}

A1到达循环后,收集新列表中的相关字符串并将其从现有列表中删除

正在获取并发修改异常。请帮忙解决这个问题

输出: 新版本:A1、A2、A3 测试:A1B1,C1

newLst:A1B1 测试:C1

newLst:C1


共 (3) 个答案

  1. # 1 楼答案

    可以从using stream开始过滤出元素:

    List<String> result = test.stream()
                .filter(line -> line.startsWith("A")) 
                .collect(Collectors.toList()); 
    result.forEach(System.out::println);  //This is for printing elements
    
  2. # 2 楼答案

    为什么你会得到ConcurrentModificationException

    这是因为您试图在迭代集合的项目时修改集合。在迭代过程中修改集合的唯一安全方法Iterator.remove();这同样适用于Iterator.add()(无论是删除还是添加一个被视为修改的项目)

    JDK<;8解决方案

    List<String> sourceList = new ArrayList();
    List<String> destList = new ArrayList();
    sourceList.add("A1");
    sourceList.add("A2");
    sourceList.add("A3");
    sourceList.add("A1B1");
    sourceList.add("C1");
    Iterator<String> iterator = sourceList.iterator();
    
    while (iterator.hasNext()) {
        String s = iterator.next();
        if(s.startsWith("A"){
            destList.add(s);
            iterator.remove(s);
        }
    }
    

    JDK>;8解决方案

    List<String> destList = sourceList.stream()
          .filter(item -> item.startsWith("A")) 
          .collect(Collectors.toList());
    

    请注意,Java streams使用Spliterator,这与Iterator非常不同

    A stream source is described by an abstraction called Spliterator. As its name suggests, Spliterator combines two behaviors: accessing the elements of the source (iterating), and possibly decomposing the input source for parallel execution (splitting).

    欲知更多详情,我建议您查看这篇关于how streams works under the hood的有趣帖子

  3. # 3 楼答案

    您可以使用一个显式的Iterator来迭代List,并在循环中使用Iteratorremove()方法(而不是Listremove()),但是从test中删除在循环之后添加到newLst的所有元素会更简单:

    for(String s: test){
        if(s.startsWith("A"){
            newLst.add(s);
        }
    }
    test.removeAll(newLst);