0

How can I update an item the arraylist using stream, example I want to update item 1 from 100 to 1000:

    List<PayList> payList = new ArrayList<>();
    payList.add(new PayList(1, 100));
    payList.add(new PayList(2, 200));

I am able to find the index, but how can I find the index and then update the value?

   int indexOf = IntStream.range(0, payList.size())
                            .filter(p -> trx.getTransactionId() == 
   payList.get(p).getTransactionId())
                            .findFirst().orElse(-1);
2
  • Is PayList mutable? Does it have a method like setAmount to update 100 to 1000? Commented Jun 13, 2021 at 2:53
  • @roby it's not mutable, yes it has setAmount method. Commented Jun 13, 2021 at 2:53

1 Answer 1

1

A couple of options:

Using the index you have already obtained, you can use paylist.get(index) again. However you must handle the missing -1 case:

int indexOf = IntStream.range(0, payList.size())
                       .filter(p -> trx.getTransactionId() ==
                                    payList.get(p).getTransactionId())
                       .findFirst().orElse(-1);
if(indexOf == -1) {
    // handle missing
}else {
    payList.get(indexOf).setAmount(1000);
}

If you don't need to handle the missing case you could stream over the lists like this:

final Stream<PayList> filtered = payList.stream().filter(p -> trx.getTransactionId() == p.getTransactionId());
final Optional<PayList> first = filtered.findFirst();
first.ifPresent(i -> i.setAmount(1000));

Or you could use similar orElse, ifPresentOrElse, orElseThrow type logic on the optional to handle the missing case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.