Cyrus Cyrus - 3 years ago 72
Android Question

How to get element index when using a stream to traverse a list?

I want to get index when traverse list use lambda.

For example:

List<CheckBox> checkBoxes = null;

checkBoxes.forEach(checkBox -> {
if (checkBox.isSelected()) {
sb.append("index"); //I want to get checkbox index here

checkBoxes = null;
is just a placeholder but will be used properly once I start writing some code.

Answer Source

Here's how I would do it.

Run an IntStream over the indexes of the list. Then filter the indexes based on whether the corresponding checkbox is selected. Then map the index value, an int, into a String representation of index value. Finally, collect the strings into a result string, separated by commas.


    String result = IntStream.range(0, checkBoxes.size())
                             .filter(i -> checkBoxes.get(i).isSelected())

The output will be something like


depending upon which checkboxes are actually checked.

I would avoid using forEach since you can accomplish the goal by transforming values instead of performing side effects. I would also avoid List.indexOf since that searches the list linearly for the desired item. It's not a big deal if you have only a few checkboxes, but if you have a lot, the O(N^2) growth will cause performance to suffer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download