Skip to content
Advertisement

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

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()?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement