Reputation: 691
I have a list of Foo objects. Value for activity is different in each objects and same category can be present in several objects. I have two combo boxes in my application UI for category and activity.
public class Foo
{
String category;
String activity;
}
I need to load the category combo box from the available category values in the list of Foo objects. When someone selects a category from combo box, I need to load activity combo box from the values from Foo list that matches the selected category.
If 'all' is selected in category combo box all the activities will be loaded to the activity combo box. When user selects an activity from activity combobox, relevant category value will get loaded to the category combo box.
So it is two way connected. To implement this functionality I thought of using two maps, One that map category as key and activities as values. The other map with activity as key and category as value.
Is there any other way than using 2 maps to implement this functionality?
Upvotes: 0
Views: 29
Reputation: 2534
If you don't have a lot of elements in these comboboxes you could use stream api to get the elements:
public List<String> getActivitiesForCategory(List<Foo> fooList, String category) {
return fooList.stream()
.filter(foo -> foo.getCategory().equals(category))
.map(Foo::getActivity)
.collect(Collectors.toList());
}
public List<String> getCategoriesForActivity(List<Foo> fooList, String activity) {
return fooList.stream()
.filter(foo -> foo.getActivity().equals(activity))
.map(Foo::getCategory)
.collect(Collectors.toList());
}
but if you have a lot of elements this may not be a very efficient way. In this case two maps:
category -> List<> activities
activity -> List<> categories
will be a better choice
Upvotes: 1