从Java ArrayList中删除而不进行迭代 [英] Removing from Java ArrayList without iteration

查看:46
本文介绍了从Java ArrayList中删除而不进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一项作业,但是我找不到一种使这项工作正常进行的方法.我有一个ArrayList,上面有5位学生的信息.我需要构造一个将删除其中一个对象的方法,但是由于它是静态删除,因此不需要/不需要迭代.我有以下代码:

I am working on an assignment, and I can't find a way to make this work properly. I have an ArrayList with information on 5 students. I need to construct a method that will remove one of the objects, but I do not need/want iteration, as it is a static removal. I have the following code:

import java.util.ArrayList;
import java.lang.String; 

public class Roster {
static ArrayList<Student> myRoster = new ArrayList<>();

public static void main(String[] args){

//Add Student Data
    Roster.add("1","John","Smith");
    add("2","Suzan","Erickson");
    add("3","Jack","Napoli");
    add("4","Erin","Black");
    add("5","Jason","Rapp");

remove("3");
remove("3");

}

public static void add(String studentID, String fName, String lName){
    Student newStudent = new Student(studentID, fName, lName);
myRoster.add(newStudent);
}

public static void remove(String studentID){
    if (myRoster.contains(studentID)){
        Roster.remove(studentID);
    }
    else {
        System.out.println("This student ID does not exist.");
    }
}

当我编译代码时,没有任何条目会被删除,并且 else 语句会为两个 remove 调用触发.

When I compile the code, none of the entries are removed, and the else statement fires off for both remove calls.

推荐答案

myRoster Student 对象的 List . List 包含 remove 仅适用于类似对象,不适用于 String 值-它不知道如何匹配一个 String 对一个 Student 的人.

myRoster is a List of Student objects. List contains and remove will work against only like objects, not String values - it has no idea how to match a String against a Student.

作为替代方案,您可以使用 List Stream 支持和 filter List 的支持匹配 studentID 的元素,然后删除所有这些元素,例如...

As an alternative, you could make use of List's Stream support and filter the List for elements which match the studentID and then remove all those elements, for example...

public static void remove(String studentID) {
    List<Student> matches = myRoster.stream().filter(student -> student.getStudentID().equals(studentID)).collect(Collectors.toList());
    myRoster.removeAll(matches);
}

但是我不需要/想要迭代

but I do not need/want iteration

就这样,您仍然了解到,仍然有一个迭代在执行,只是您自己没有在做,API是

Just so you understand, there is still an iteration been performed, it's just that you're not doing it yourself, the API is

这篇关于从Java ArrayList中删除而不进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆