java - 如何获取 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
输出应该是这样的:如果我打印crimeList
和normal 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 流 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());
推荐阅读
- laravel - Laravel - 如何在 chartjs 饼图中同时显示计数和百分比 (%)
- powershell - 将复制命令行从批处理转换为 powershell
- c# - C# 和 LINQ.XML 从 XML 中选择
- javascript - 键入自定义渲染器 [ Gatsby 和内容丰富的 Richtext ]
- java - Spring Boot 和 GraalVM 原生镜像
- gcloud - 为什么我的 gcloud 命令在 WSL2 中突然变得很慢
- reactjs - 在 ReactDOM.render(...) 之前更新 redux-store
- android - 如何解决未解析的参考片段?
- android - 在 Kotlin 中,我应该在哪里定义一个类中的可重用回调?
- visual-studio-code - 由于验证错误,发布 vscode 扩展失败:“包含一个提取不安全的条目”