bhxbr922
bhxbr922

Reputation: 47

How to create new objects using loop

I would like to know if it is possible to go through the list and create the object, enter the values of the list elements in the constructor. For example:

String result = "1 2 3 4 5 6";
String list[]=result1.split(""); // create a list of String
//next i want to do the following
BigInteger a1 = new BigInteger (l1);// String l1 = "1";String l2 = "2";
BigInteger a2= new BigInteger (l2);
BigInteger result = a1.add(a2);
etc

Is it possible to do that using for each loop? How it should look like? Thanks

Upvotes: 1

Views: 84

Answers (5)

AgentP
AgentP

Reputation: 7220

Yes it's possible, One way to do this is

    String result = "1 2 3 4 5 6";
    String list[]=result.split(" "); // create a list of String

    //Create A Array of objects

    BigInteger[] objects=new BigInteger[list.length];
    BigInteger sum = new BigInteger("0"); // initializing with 0

    for(int i=0;i<list.length;i++)
    {
        objects[i]=new BigInteger(list[i]);
        sum=sum.add(objects[i]);// Assign each objects

    }
    System.out.println("Sum : "+sum); // print sum

Upvotes: 0

Mahmoud Ali
Mahmoud Ali

Reputation: 11

    String result = "1 2 3 4 5 6";
    String list[]=result.split(" "); 
    // You should split using space " " to create this list: {"1","2","3","4","5","6"}
    
    BigInteger [] objects = new BigInteger[list.length];
    BigInteger sum = new BigInteger("0"); // initialize sum with Zero
    for(int i = 0 ; i < objects.length ; i++){
        objects[i] = new BigInteger(list[i]);
        sum = sum.add( objects[i] ); // Add the value of each BigInteger to sum
    }

Upvotes: 1

Michal Kov&#225;čik
Michal Kov&#225;čik

Reputation: 31

Yes it is. Functionally like this:

List<BigInteger> integers = Arrays.stream(list).map(x -> new BigInteger(x)).ToList();

if you want to sum:

BigInteger sum = Arrays.stream(list).map(x -> new BigInteger(x)).reduce(0, (a, b) -> a+b);

Same can be done with for loops but with more code

Upvotes: 0

tdranv
tdranv

Reputation: 1340

You can have one BigInteger outside the loop and inside do:

    BigInteger sum = BigInteger.ZERO;
    
    String result = "1 2 3 4 5 6";
    String list[] = result.split(" ");
    for (int i = 0; i < list.length; i++) {
        sum.add(BigInteger.valueOf(Integer.parseInt(list[i])));
    }

Upvotes: 0

Mureinik
Mureinik

Reputation: 311383

Indeed, you could use a loop to go over the split array and accumulate the results in a list:

List<BigInteger> results = new ArrayList<>(list.length);
for (str : list) {
    results.add(new BigInteger(str));
}

You could also use a stream, which would arguably be more elegant, although it's matter taste:

List<BigInteger> result = 
    Arrays.stream(list)
          .map(BigInteger::new)
          .collect(Collectors.toList());

Upvotes: 1

Related Questions