I have the following piece of code which groups the given entries (activities, which is Iterable<activity>) based on IDs.
For the final result, I want it to return a Map of ID to Iterables of the entries grouped by that ID.
For example: Map<String, Iterables<activity>>.
Right now, it returns a Map<String, List<activity>>.
stream(activities)
.collect(
groupingBy(
activity -> {
if (activity.getID()) {
return activity.getID();
} else {
return activity.getName();
}
}));
I am unable to figure out a way to do this.
There's no such notion in Java as truthy values, which exists in languages like javascript. I.e.
Stringcan't be resolved intobooleanautomatically (what your code attempts to do).There are multiple ways of how you can check whether the given value is
nulland provide an alternative value.If
nameattribute is guaranteed to be non-null you can use static methodrequireNonNullElse()of theObjectsutility class:If
nameattribute is nullable, then you have to provide a default value that will be used in case if bothidandnameequal tonull. Becausenullkey is not allowed withCollectors.groupingBy()and will result inNullPointerExceptionat runtime.For the case when both field could be
nullI suggest extracting the logic for obtaining the key into a separate method.Which can be used inside the collector like that:
Sidenote: by convention, names of classes in Java should start with a capital letter:
Student,Employee,Activity.