Java如何修改ArrayList中存储的指定对象的特定成员属性
前置修正说明
先修正你代码中存在的问题,才能正常实现修改逻辑:
- 命名规范问题:Java类名需使用大驼峰命名,你定义的
constructor类名既不符合规范,也和Java中「构造方法」的术语冲突,建议修改为CountryInfoItem;另外拼写错误Contry应修正为Country。 - 私有属性访问问题:类成员属性用
private修饰后,必须提供对应的getter/setter方法才能对外读取和修改属性值。 - 语法错误:业务方法、main方法中存在返回值拼写错误、方法名大小写不一致的问题,需先修正。
修正后的基础代码如下:
// 实体类 import java.math.BigDecimal; class CountryInfoItem { private Country country; private BigDecimal population; private String capital; public CountryInfoItem(Country country, BigDecimal population, String capital){ this.country = country; this.population = population; this.capital = capital; } // 以下为新增的getter/setter方法 public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public BigDecimal getPopulation() { return population; } public void setPopulation(BigDecimal population) { this.population = population; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } }
// 业务类 import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class CountryInfo { public List<CountryInfoItem> information(Country country, BigDecimal population, String capital) { List<CountryInfoItem> countriesInfo = new ArrayList<>(); countriesInfo.add(new CountryInfoItem(country, population, capital)); return countriesInfo; } }
解决方案
方案1:普通增强for循环(逻辑直观,适合新手)
遍历列表匹配目标对象,直接调用setter修改属性:
import java.math.BigDecimal; import java.util.List; public static void main(String[] args) { // 假设Germany是你已经实例化好的Country类对象 List<CountryInfoItem> exampleList = new CountryInfo().information(Germany, new BigDecimal("80"), "Berlin"); // 遍历修改 for (CountryInfoItem item : exampleList) { if (item.getCountry().equals(Germany)) { item.setPopulation(new BigDecimal("85")); // 匹配到目标后直接跳出循环,减少不必要的遍历 break; } } }
方案2:Stream流实现
你之前使用map没成功大概率是没有正确调用setter修改属性,或者没有处理返回结果,正确写法如下:
// 需要生成新列表的场景 exampleList = exampleList.stream() .map(item -> { if (item.getCountry().equals(Germany)) { item.setPopulation(new BigDecimal("85")); } return item; }) .collect(Collectors.toList());
如果只需要修改原列表的元素,不需要生成新列表,用filter+findFirst写法更简洁:
exampleList.stream() .filter(item -> item.getCountry().equals(Germany)) .findFirst() .ifPresent(item -> item.setPopulation(new BigDecimal("85")));
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

