如何获取数组列表中的特定列表或项



我使用ArrayList<Model>根据我的模型类

和My Model类是这样的:

public class Model{
String name;
int age;
public Model(){}
public Model(String name, int age){
this.name = name;
this.age = age;
}
//and getters and setters for name & age.
}

所以我只想访问包含特定名称的列表或项或字段

我总共有三个列表一个是arrayList<Model>();,它有数据第二个是

crimeList<Model>();,另一个是normalList<Model>();

所以我想把数据存储到crimeList<Model>();它的名字是"joker""morris"

normalList<Model>();(名字不是"joker""morris")

//can I do something like this
for(int i =0; i<arrayList.size(); i++){
if(arrayList.contans("Joker")){
crimeArrayList.add(arrayList.get(thatContains("Joker")));
}
}
//like this
输出应该是这样的:如果我打印crimeListnormal list
Crime list [name = Joker, age = 29, name = Morris age = 30, name = Joker age = 30, name = Morris age = 20] //and if more people found 
//with these names then add also to crime List;
Normal List [name = James age = 18, name = Bond age = 18, name = OO7 age = 19] //and so on...

有人能帮我吗?任何答案或解决方案都是赞赏的

罪犯名单:

List<String> criminalNames = Arrays.asList("Joker","Morris");

假设你有一个数据列表:

List<Model> arrayList = new ArrayList<>();
arrayList.add(new Model("Joker", 29));
arrayList.add(new Model("Morris", 30));
arrayList.add(new Model("Joker", 30));
arrayList.add(new Model("Morris", 20));
arrayList.add(new Model("James", 18));
arrayList.add(new Model("Bond", 18));
arrayList.add(new Model("007", 19));

获取犯罪列表:

List<Model> crimeList = new ArrayList<>();
for(Model model : arrayList){
if(criminalNames.contains(model.getName())){
crimeList.add(model);
}
}

获取正常列表:

List<Model> normalList = new ArrayList<>();
for(Model model : arrayList){
if(!criminalNames.contains(model.getName())){
normalList.add(model);
}
}

打印结果:

System.out.println("Crime list: " + crimeList);
System.out.println("Normal List: " + normalList);
一个更优雅的解决方案是使用Java流APIstream().filter:

List<Model> crimeList = arrayList.stream()
.filter(model -> criminalNames.contains(model.getName()))
.collect(Collectors.toList());
List<Model> normalList  = arrayList.stream()
.filter(model -> !criminalNames.contains(model.getName()))
.collect(Collectors.toList());
List<Model> crimeList = new ArrayList<>();
List<Model> normalList = new ArrayList<>();
models.forEach(model -> {
if (model.name.equals("joker") || 
model.name.equals("morris")) {
crimeList.add(model);
} else {
normalList.add(model);
}
})
如果需要,可以使用contains而不是=

函数。如果大小写字母也很重要,则使用toUpperCase()toLowerCase()

可以也可以使用流:

List<Model> crimeList=new ArrayList<>();
List<Model> normalList=new ArrayList<>();
crimeList=models.stream()
.filter(m-> m.name.equals("joker") || 
m.name.equals("morris"))
.collect(Collectors.toList());

最新更新