Hey I'd like to ask if there is any way that I can use the Kotlins forEachIndexed() function for lists in Java? I searched everywhere but I couldn't find anything. I want to iterate over a list of ImageButtons and to each list item I want to set an Image from another list of bitmap image. So in Kotlin it would be:
buttons.forEachIndexed{index, button ->
button.setOnclickListener{
button.setImageResource(images[index])
}
}
The way I am iterating over buttons is
for(ImageButton button: buttons)
but I don't have any way to iterate over the indices. Can I somehow turn the Kotlin code above to Java?
Here is my code so far:pastebin.com/Rh9vcNbz
CodePudding user response:
If you have the Kotlin stdlib in the project but are working on a Java file, you can use Kotlin's forEachIndexed
from Java. It's not particularly pretty but it's doable:
import kotlin.collections.CollectionsKt;
...
CollectionsKt.forEachIndexed(list, (index, element) -> {
doSomething();
return Unit.INSTANCE;
});
CodePudding user response:
I work with Java and Kotlin for some years now and sadly I think that there is nothing in Java (atleast which is standard) that can deliver you something like Kotlin does with its forEachIndexed.
I mean if you look at the implementation of the "forEachIndexed"...
It is nothing more then this:
var index = 0
for (item in this) action(checkIndexOverflow(index ), item)
it basically creates an int variable for you, and increments it, while iterating over the List and invoking your Lambda.
If you still want something similar, which is still "hacky" - I wrote something for you, not that I want to say that it is perfect but does the job - and it is still generic.
New Classes:
public interface IndexedAction<T> {
void action(T item, int index);
}
public class ExtendedArrayList<T> extends ArrayList<T> {
public void forEachIndexed(IndexedAction<T> indexedAction) {
int i = 0;
for (T element : this) {
indexedAction.action(element, i);
i ;
}
}
}
Usage:
@Test // Robolectric Unit Test
public void myTest() {
ExtendedArrayList<Bitmap> bitmapArray = new ExtendedArrayList<>();
ExtendedArrayList<ImageButton> buttons = new ExtendedArrayList<>();
Application context = RuntimeEnvironment.application;
int width = 200;
int height = 100;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmapArray.add(bitmap);
bitmapArray.add(bitmap);
bitmapArray.add(bitmap);
bitmapArray.add(bitmap);
Collections.shuffle(bitmapArray);
ImageButton button1 = new ImageButton(context);
ImageButton button2 = new ImageButton(context);
ImageButton button3 = new ImageButton(context);
ImageButton button4 = new ImageButton(context);
buttons.add(button1);
buttons.add(button2);
buttons.add(button3);
buttons.add(button4);
buttons.forEachIndexed((button, index) ->
button.setImageBitmap(bitmapArray.get(index)));
}