Search code examples
javastringlistarraylistmaterialbutton

Applying a function to list values and creating a resultant array with less code


I understand that what I have currently is maybe better for readability, but I am just interested in the different ways I could achieve the same result with less code.

ArrayList<MaterialButton> buttons = new ArrayList<>();

// grab button states and write to database
        String[] buttonStates = new String[buttons.size()];

        for (int i = 0; i < buttons.size(); i++) {
            buttonStates[i] = String.valueOf(buttons.get(i).isChecked());
        }

Appreciate any input I can get on this!


Solution

  • You can use the java stream api for that:

    String[] buttonStates = buttons.stream()
      .map(MaterialButton::isChecked) //maps to boolean (assuming isChecked returns boolean)
      .map(String::valueOf) //maps to String
      .toArray(String[]::new); //collects all Strings into an array
    

    The String[]::new is a Function that takes the number of elements as an argument, meaning it creates a new String[buttons.size()].