Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 257
Stefan Lindner Avatar asked Feb 28 '26 09:02

Stefan Lindner


1 Answers

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.

like image 139
Eran Avatar answered Mar 02 '26 21:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!