Skip to content
Advertisement

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
          sb.append(",");
      }
});

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

Advertisement

Answer

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.

Code:

    String result = IntStream.range(0, checkBoxes.size())
                             .filter(i -> checkBoxes.get(i).isSelected())
                             .mapToObj(String::valueOf)
                             .collect(Collectors.joining(","));

The output will be something like

    0,1,3,6

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.

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