-1

(I am a beginner so if I called something wrong ply correct me) I made an ArrayList from different Objects. But I don't know how can I change a specific Object on my ArrayList. For example, change population from 80 to 85 in below example. Contractor:

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;
  }

and my method:

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

and my main

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

I tried to use stream().map but wasn't successful to find a way. Will be happy if you guys write the solution to my problem.

Jan
  • 1
  • 1
  • 2
    You should be studying tutorials or textbooks on the basics of Java before attempting this. You have not understood the basics of a constructor method, nor basic Java naming conventions. Not a good Question for this site. – Basil Bourque Sep 16 '21 at 19:06

1 Answers1

0

First of all, you have to A) add setters to change the value of your variables or B) do them as public to be visible variables.

List#get method, with int as parameter represents the index of the element in this list which is to be returned (exampleList.get(0) will return the 1st element)

By using the A) solution (with setters):

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

By using the B) solution:

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

In stream case now, you have to add a filter to be applied in order to return the desired object.

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

And ofcourse, you can just use a simple loop and check the value

//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);
}
Melron
  • 569
  • 4
  • 10