-1
ABC abc = eMsg.getAbcCont().stream()
                        .filter(cnt -> (option.geiID().equals(cnt.getId()) && option.getIdVersion() == cnt.getIdVersion()))
                        .collect(Collectors.toList()).get(0); 
delEmsg.getAbcCont().remove(abc);

Above code is giving me en exception as

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)

getAbcCont method will return the List of ABC objects.Currently my eMsg contains two object with the getAbcCont. When control reach to the .collect(Collectors.toList()).get(0); its giving the above mentioned exception. Any help suggestion must be appricaited.

Naman
  • 27,789
  • 26
  • 218
  • 353
Zia
  • 1,001
  • 1
  • 13
  • 25
  • 2
    Possible duplicate of [Understand Arraylist IndexOutOfBoundsException in Android](https://stackoverflow.com/questions/21570318/understand-arraylist-indexoutofboundsexception-in-android) – Naman Sep 10 '18 at 11:11
  • The answer is worth a read in the link above and shall drive you better understand instead just making a quick fix. – Naman Sep 10 '18 at 11:12

2 Answers2

4

This means that the result after the filter is zero elements, so you cannot do get(0).

A quick solution for this would be to first get the list of elements back, and then check if there is atleast one element.

List<ABC> list = ABC abc = eMsg.getAbcCont().stream()
                        .filter(cnt -> (option.geiID().equals(cnt.getId()) && option.getIdVersion() == cnt.getIdVersion()))
                        .collect(Collectors.toList());

if(list.size() > 0){
 ABC abc = list.get(0);
}

Obviously there is a shorter way also using lambdas such as:

ABC abc = eMsg.getAbcCont().stream()
                        .filter(cnt -> (option.geiID().equals(cnt.getId()) && option.getIdVersion() == cnt.getIdVersion()))
                        .collect(Collectors.toList()).findFirst().orElse(null)

Reference: https://stackoverflow.com/a/26126636/1688441

But as User nullpointer , you might need to check if an element is found before you try to call remove() using object abc. I suspect trying to remove null from a collection might not do anything, but you could check to be sure!

if(abc != null){
 delEmsg.getAbcCont().remove(abc);
}
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • 2
    I think you missed `delEmsg.getAbcCont().remove(abc);` in the question...`orElse(null)` can result into a possible NPE here. – Naman Sep 10 '18 at 11:19
0

You should do !list.isEmpty() rather than list.size() as per sonar