Home > other >  Find the position of lastIndexOf a List that start with a certain character in kotlin/Java
Find the position of lastIndexOf a List that start with a certain character in kotlin/Java

Time:04-28

var list_a = listOf("00:00", "09:00", "20:00", "23:00", "01:00", "03:00")

// i want to return the position of "23:00" in list_a

var list_b = listOf("00:10", "00:30", "09:00", "21:10")

// i want to return the position of "21:10" in list_b

how do i write a function to get the position of starting with 2X:XX? How can I mix lastIndexOf() and startsWith()

CodePudding user response:

You can use normal for-loops, i.e.

int getIndexOfLastStringStartingWith2(List<String> list) {
   for (int i = list.size() - 1; i > 0; i--) {
      if (list.get(i).startsWith("2")) {
        return i;
      }
   }

  return -1; 
}

This will return the index of the last string in the list starting with 2.

CodePudding user response:

how do i write a function to get the position of starting with 2X:XX? How can I mix lastIndexOf() and startsWith()

This method will get the postion:-

public int getPos(List <String> list) {
   for (String a : list) {
      if(a.startsWith("2")){
         
            return list.indexOf(a);

        }
   }
return -1;
}

Then to use it:-

var list_a = listOf("00:00", "09:00", "20:00", "23:00", "01:00", "03:00")
int pos = getPos(list_a);
  • Related