java 从 ArrayList 中删除具有特定值的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29107398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove items from ArrayList with certain value
提问by NLMDEJ
I have created a list of objects and have people added to it:
我创建了一个对象列表并添加了人员:
ArrayList<Person> peeps = new ArrayList<Person>();
peeps.add(new Person("112", "John", "Smith"));
peeps.add(new Person("516", "Jane", "Smith"));
peeps.add(new Person("114", "John", "Doe"));
I am trying to figure out how to remove the person from the list by ID number. So if I wanted to remove the person with the ID number 114 but didn't now where it fell in the list, how would I?
我想弄清楚如何通过 ID 号从列表中删除此人。因此,如果我想删除 ID 号为 114 的人,但现在没有删除它在列表中的位置,我该怎么办?
采纳答案by vandale
If you are going to be using an ArrayList, the the only way is to go through the entire list, looking at each person, and seeing it their id number is 114. For larger datasets, this is not going to efficient and should be avoided.
如果您打算使用 ArrayList,唯一的方法是遍历整个列表,查看每个人,看到他们的 id 号是 114。对于较大的数据集,这不会有效,应该避免.
If you can change your data structure, then some sort of Mapwould be better (HashMapis typically a good choice). You could have the id number as a "key" and then associate it with each person. Later you can query the Map by key. The con is you can only have one value as a key, so you can't have say both name and id number keys
如果您可以更改数据结构,那么某种Map会更好(HashMap通常是一个不错的选择)。您可以将 id 号作为“密钥”,然后将其与每个人相关联。稍后您可以通过键查询 Map。缺点是你只能有一个值作为键,所以你不能同时说 name 和 id 数字键
Edit:
An more efficient way to do use an ArrayList would be to keep it sorted by id number. Then you can use something like Collections.binarySearch()to quickly access the elements by id number. The con is is that it is expensive to remove from/insert into a sorted array, as everything greater the element has to be moved. So if you are going to be doing relatively few changes compared to the number of reads, this might be viable
编辑:
使用 ArrayList 的一种更有效的方法是将其按 id 编号排序。然后你可以使用类似Collections.binarySearch() 的东西来通过 id 号快速访问元素。缺点是从排序数组中删除/插入是很昂贵的,因为必须移动元素更大的所有内容。因此,如果与读取次数相比,您要做的更改相对较少,这可能是可行的
回答by Paul
Using Java8:
使用 Java8:
peeps.removeIf(p -> p.getId().equals("112"));
Note that this is equivalent to linear search and will take O(n)
time. If this operation will be repeated frequently it is recommended to use a HashMap
in order to speed things up to O(1)
.
请注意,这等效于线性搜索,并且需要O(n)
时间。如果此操作将频繁重复,建议使用 aHashMap
以加快速度O(1)
。
Alternatively using a sorted list would also do the trick, but require O(log n)
time.
或者,使用排序列表也可以解决问题,但需要O(log n)
时间。
回答by Noam Shaish
There are many ways to tackle this.
有很多方法可以解决这个问题。
- I am using CollectionUtils from apache.common.collection4 or its google equivalent. and then select what you wish using a predicate or in java 8 an lambda expression.
- 我正在使用 apache.common.collection4 中的 CollectionUtils 或其谷歌等效项。然后使用谓词或在 java 8 中选择您想要的 lambda 表达式。
CollectionUtils.select(peeps, new Predicate<Person>() {
@Override
public boolean evaluate(Person object) {
return object.getId().equals("114");
}
});
- use good old iterator and loop over it
- 使用好的旧迭代器并循环它
Iterator<Person> iterator = peeps.iterator();
while(iterator.hasNext()) {
Person next = iterator.next();
if(next.getId().equals("114")) {
iterator.remove();
}
}
回答by adrCoder
iterate
in the ArrayList
elements and remove the ones which match the string you want to remove:The Iterator remove
operations is safe and does not create a ConcurrentModificationException
iterate
在ArrayList
元素和删除与您要删除的字符串,它的那些:该Iterator remove
操作是安全的,不会产生ConcurrentModificationException
for (Iterator<String> iterator = peeps.iterator(); elementToCheck = iterator.next();) {
if (elementToCheck.getId().equals("112")) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
回答by m0skit0
You first need to have a working equals
in your Person class (which you should). Then you can just use List#indexOf
and List#remove
. For example:
你首先需要equals
在你的 Person 类中工作(你应该这样做)。然后你就可以使用List#indexOf
and 了List#remove
。例如:
final Person toRemove = new Person("112");
peeps.remove(peeps.indexOf(toRemove));
(assuming the Person ID is unique).
(假设个人 ID 是唯一的)。
Alternatively if your list is an ArrayList
you can use ArrayList#remove(Object)
:
或者,如果您的列表是一个,ArrayList
您可以使用ArrayList#remove(Object)
:
final Person toRemove = new Person("112");
peeps.remove(toRemove);
If you're using Java 8, you can use Paul's solution.
如果您使用的是 Java 8,则可以使用Paul 的解决方案。
回答by Jobin Thomas
class Processor{
ArrayList<Person> peeps = new ArrayList<Person>();
void setPeeps(){
peeps.add(new Person(112, "John", "Smith"));
peeps.add(new Person(516, "Jane", "Smith"));
peeps.add(new Person(114, "John", "Doe"));
}
void removePerson(int id){
for(int i=0; i <= peeps.size(); i++){
Person person = peeps.get(i);
if(person.id == id)
peeps.remove(peeps.get(i));
}
}
void displayPersonsList(){
for(Person person : peeps){
System.out.println(person.id + ":" + person.fName + ":" + person.lName);
}
}
public static void main(String args[]){
Processor objProcessor = new Processor();
objProcessor.setPeeps();
objProcessor.removePerson(114);
objProcessor.displayPersonsList();
}
}
class Person{
int id;
String fName;
String lName;
public Person(int id, String fName, String lName){
this.id = id;
this.fName = fName;
this.lName = lName;
}
}