0

I have List of Customer object. I want to iterate over list and increment orders by one.

I tried with for each but here I had to create new list and add values in it.

class Customer{
    long id;
    int orders;
    //getters setters constructor
}

List<Customer> empList=Arrays.asList(new Customer(1,10),new Customer(2,,20));

List<Customer> empList1=new ArrayList<>();
empList.forEach(e->{
    e.orders++; //updating orders
    empList1.add(e);
}); 

Is there a better way to do this? I tried with streams but it is only mapping the orders

empList.stream().map(e->{e.orders++;}).collect(Collectors.toList());
3
  • you can use peek Commented Apr 22, 2019 at 11:21
  • 2
    You don’t need to create an another list emp1 as you are not modifying the structure of the list you are modifying the existing elements which is an object in this case. As you are using foreach which is a consumer in this case. Your fix should be e.setOrders(e.orders += 1). Then it will just update the existing list. Commented Apr 22, 2019 at 11:27
  • Possible duplicate of Modify property value of the objects in list using java 8 streams Commented Apr 22, 2019 at 12:11

2 Answers 2

3

You can use peek

empList.stream().peek(e->{e.orders++;}).collect(Collectors.toList());

Also as correctly pointed by "Vasanth Senthamarai Kannan " you don't need second list as you are not modifying structure of list,

empList.forEach(e->e.orders++);
Sign up to request clarification or add additional context in comments.

3 Comments

Or shorter: empList.forEach(e -> e.orders++);
@Holger.. Yes.. Appreciate your feedback
Peek method should only be used for debugging docs.oracle.com/javase/8/docs/api/java/util/stream/…
0

you can use replaceAll() just define a method like incrementOrder()

empList.replaceAll(Customer::incrementOrder);


  public Customer incrementOrder(){
    this.orders+=1;
    return this;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.