我有一个我想要迭代的对象列表,并且对于具有特定值的所有对象,将它们添加到新列表中。我能做到这一点还是需要一张地图? 示例代码:
List<Object> object = new ArrayList();
Iterator iterator = object.iterator();
while(iterator.hasNext()){
Object listobject = (Object)iterator.next();
if(object.getId() == 1){
newlist.add(object);
上面的代码只添加了第一个带有此id的对象。如何在新列表中添加具有此id的所有对象? thanx的建议。
答案 0 :(得分:1)
public class ObjectCollector {
static class LstObj {
int id;
String name;
public int getId() {
return id;
}
public LstObj(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "LstObj [id=" + id + ", name=" + name + "]";
}
}
public static void main(String[] args) {
List newlist = new ArrayList();
List objects = new ArrayList();
//Populating random objects
objects.add(new LstObj(1, "Name 1"));
objects.add(new LstObj(2, "Name 2"));
objects.add(new LstObj(1, "Name 1"));
objects.add(new LstObj(1, "Name 1"));
objects.add(new LstObj(3, "Name 3"));
objects.add(new LstObj(4, "Name 4"));
Iterator iterator = objects.iterator();
while(iterator.hasNext()){
LstObj listobject = (LstObj)iterator.next();
if(listobject.getId() == 1){
newlist.add(listobject);
}
}
System.out.println(newlist);
}
}
For-each method
import java.util.ArrayList;
import java.util.List;
public class ObjectCollector {
static class LstObj {
int id;
String name;
public int getId() {
return id;
}
public LstObj(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "LstObj [id=" + id + ", name=" + name + "]";
}
}
public static void main(String[] args) {
List<LstObj> newlist = new ArrayList<LstObj>();
List<LstObj> objects = new ArrayList<LstObj>();
// Populating random objects
objects.add(new LstObj(1, "Name 1"));
objects.add(new LstObj(2, "Name 2"));
objects.add(new LstObj(1, "Name 1"));
objects.add(new LstObj(1, "Name 1"));
objects.add(new LstObj(3, "Name 3"));
objects.add(new LstObj(4, "Name 4"));
for (LstObj obj : objects) {
if (obj.getId() == 1) {
newlist.add(obj);
}
}
System.out.println(newlist);
}
}
答案 1 :(得分:-1)
您可以使用番石榴库。它允许您使用谓词过滤列表。因此,您只获得列表中的ID作为您想要的ID。
例子: