首页 > 解决方案 > 如何获取 ArrayList 中的特定列表或项目

问题描述

ArrayList<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...

谁能帮我?任何答案或解决方案表示赞赏

标签: javaarraylist

解决方案


罪犯名单:

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 流 API stream().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());

推荐阅读