Simon Ho
Simon Ho

Reputation: 598

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

Upvotes: 0

Views: 432

Answers (3)

Praveen
Praveen

Reputation: 3486

To find the last matching index of an item for any condition, use indexOfLast extension function of the list.

list_b.indexOfLast {
    it.startsWith("2")
}

To find the last item in the list, a more idiomatic approach would be to use methods provided by Kotlin, rather than making a new method.

list_b.findLast {
    it.startsWith("2")
}

This would return the last item that starts with 2 or null if it's not in the list. If you don't want it to return null, you can use the Elvis operator.

list_b.findLast {
    it.startsWith("2")
} ?: ""

This would return an empty string if no item is found.

Upvotes: 2

skorpilvaclav
skorpilvaclav

Reputation: 77

In Kotlin u can use indexOfLast function which returns index of the last element matching the given predicate, or -1 if the array does not contain such element.

list.indexOfLast {  
  it.startsWith("2")
}

Upvotes: 1

cooleee
cooleee

Reputation: 134

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.

Upvotes: 3

Related Questions