Stefan Lindner
Stefan Lindner

Reputation: 329

How to filter keysets and return values of a map with java stream api

I want to rewrite a method that loops over the keys of a map and returns the value, if the key has an attribute selected. More specific:

Map<JRadioButton, Configuration> radioButtons = ...
public Configuration getSelectedConfiguration()
      for (JRadioButton radioButton : radioButtons.keySet()) {
          if(radioButton.isSelected()){
                return radioButtons.get(radioButton);
          }
      }
}

I basically want the Configuration for the selected JRadioButton. The problem for me right now is, to figure out when and how to filter properly. My approach is not compiling right now, since it says:

The method filter(Predicate>) in the type Stream> is not applicable for the arguments (( keys) -> {})

There are some types in this error message above as well, but i can´t edit that properly.

List<JRadioButton> selectedButtons = Stream.of(radioButtons.keySet()).filter(keys -> {
        keys.forEach(key -> {
                key.isSelected();
            });
    }).collect(Collectors.toList());

// I want to get rid of this assertion if possible      
assert ( selectedButtons.size()==1 );

return radioButtons.get(selectedButtons.get(0));

The radio buttons are grouped in a ButtonGroup, so i am sure that there will only be one selected. If there is a possibility that i don´t need the Collectors.toList() that´s fine for me too.

Upvotes: 3

Views: 3389

Answers (1)

Eran
Eran

Reputation: 394126

You are supposed to filter a single key each time. You can do it by simply passing a method reference of the isSelected method to filter:

List<JRadioButton> selectedButtons = 
    radioButtons.keySet()
                .stream()
                .filter(JRadioButton::isSelected)
                .collect(Collectors.toList());

As for getting rid to the assertion, that depends on what you want to happen if no buttons are selected or if multiple buttons are selected. If these situations are possible, you must handle them.

Upvotes: 3

Related Questions