Home > OS >  Filling a list field with sequential numbers without for loop in Java
Filling a list field with sequential numbers without for loop in Java

Time:02-03

Imagine I have a simple Person object with three fields: name (string), age (string) and order (int).

Then, I create a list of Person object (List personList), ordered by name and age (descending in my case), but with the order field initialized only, that looks like this:

"Andrew","52",0 "James","34",0 "James","28",0 "Maria","19",0

Mi goal is to fill the order field with a sequential number that shows the order in the list, something like this:

"August","52",1 "James","34",2 "James","28",3 "Maria","19",4

I achieved this using a simple For loop

for(int i=0;i<personList.size();i ) { personList.get(i).setOrden(i 1); }

Is there any cleaner / more efficient way to do this?

Thank you. Regards.

CodePudding user response:

you can use static variable which will always keep increasing , and you can assign that to your order number.

or better if you are saving your order into Db , then initilize a sequence in Db .

public class Test {

    private static int orderNo =1;
    public static void main(String args[])
    {
         createOrder("Andrew",52);
         createOrder("James",34);
         createOrder("Jemas",28);
         createOrder("Maria",19);
    }

    public void createOrder(String name , int age)
    {
        Order order = new Order(name , age , orderNo);
        orderNo  ;
        System.out.print(order);
    }

}

CodePudding user response:

Try IntStream.range from Java 8 Stream API.

IntStream.range(0, personList.size())
 .forEach(i -> personList.get(i).setOrden(i));

CodePudding user response:

You don't need Stream API for that, for-each loop is enough

int index = 1;
for(Person p : personList) {
    p.setOrder(index  );
}
  • Related