Java -更改对象数组列表的特定成员



(我是初学者,所以如果我说错了,请纠正我)我用不同的对象创建了一个数组列表。但我不知道如何改变数组列表中的特定对象。例如,在下面的例子中将人口从80改为85。承包商:

class constructor {
private Contry contry;
private BigDecimal population;
private String capital ;
public constructor(Contry contry, BigDecimal population, String capital){
this.contry = contry;
this.population = population;
this.capital = capital;
}

和我的方法:

public class ContryInfo {
public List<constructor> information(Contry contry, BigDecimal population,
String capital) {
List<constructor> contriesInfo = new ArrayList<>();
contriesInfo.add(new constructor(contry, population, capital));
return Information

和我的主

public static void main(String[] args) {
List<constructor> exampleList = new ArrayList<>();
exampleList = new ContryInfo().Information(Germany, new BigDecimal("80"), "Berlin");

我尝试使用stream()。地图,但没能成功找到方法。如果你们能写出解决我问题的方法,我会很高兴的。

首先,您必须A)添加setter来更改变量的值,或者B)将它们作为公共变量以成为可见变量。

List#get方法,以int作为参数表示列表中要返回的元素的索引(exampleList.get(0)将返回第一个元素)

通过使用A)解决方案(带setter):

exampleList.get(0).setPopulation(new BigDecimal(100));

使用B)解:

exampleList.get(0).population = new BigDecimal(100);

现在在流的情况下,你必须添加一个过滤器来应用,以便返回所需的对象。

exampleList.stream().filter(c -> c.getPopulation().intValue() == 80).findFirst().get()

当然,你可以使用一个简单的循环来检查

的值
//with getters and setters
for (constructor c : exampleList)
{
if (c.getPopulation().intValue() == 80)
c.setPopulation(new BigDecimal(100));
}
// without 
for (constructor c : exampleList)
{
if (c.population.intValue() == 80)
c.population = new BigDecimal(100);
}

最新更新