1

I have list as shown below, as this includes many repeated field values of AbcConSch

List<AbcConSch> asBeanList= tbCondition.getAbcConScheds();
AbcConSch abcSchedule = asBeanList.get(i);

this list has bag which has elements of data, so i need to get lastindexof() asBeanList with condition of field value="ConditionCode".

i have tried with below code to get value

i == asBeanList.lastIndexOf(abcSchedule.getSrConditionCode().contains(SC_CONDITION_CODE_ABC))

Thanks for helping and support in advance. Arun

Arun Kumar A
  • 93
  • 1
  • 1
  • 6

3 Answers3

3

You can implement your own lastIndexOf() method, and let it take an expression to match:

public static <E> int lastIndexOf(List<E> list, Predicate<E> predicate) {
    for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious(); )
        if (predicate.test(iter.previous()))
            return iter.nextIndex();
    return -1;
}

Test

List<String> list = Arrays.asList("AA", "BB", "ABC", "CC");
System.out.println(lastIndexOf(list, s -> s.contains("AA")));
System.out.println(lastIndexOf(list, s -> s.contains("A")));
System.out.println(lastIndexOf(list, s -> s.contains("BB")));
System.out.println(lastIndexOf(list, s -> s.contains("B")));
System.out.println(lastIndexOf(list, s -> s.contains("CC")));
System.out.println(lastIndexOf(list, s -> s.contains("C")));
System.out.println(lastIndexOf(list, s -> s.contains("DD")));

Output

0
2
1
2
3
3
-1

For your code, you'd use it like this:

List<AbcConSch> asBeanList = tbCondition.getAbcConScheds();
int i = lastIndexOf(asBeanList, a -> a.getSrConditionCode().contains(SC_CONDITION_CODE_ABC));
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

I think you have to use this way.

privat ArrayList<AbcConch>abc=new ArrayList();
List<AbcConSch> asBeanList= tbCondition.getAbcConScheds();
 for (int i=0;i<=asBeanList.size();i++{
  if(asBeanList.get(i).getSrConditionCode().contains(SC_CONDITION_CODE_ABC)){
  abc.add(asBeanList.get(i);
 }
}

and last you can get last index value

int i = abc.size()
-1

The following is the code for the Java language function List.lastIndexOf():

public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

From here, you can trivially modify it to accept an arbitrary function:

public int lastIndexOf(Object o) {

    // delete null checks (or leave in if your code requires them)

        for (int i = size-1; i >= 0; i--)
            if (yourCustomConditionHere)  // add your custom condition
                return i;

    }
cameron1024
  • 9,083
  • 2
  • 16
  • 36