Reputation: 378
I have a method as follows
public List<List<CustomClass>> categorize(List<CustomClass> customClass){
List<List<CustomClass>> returnValue = new ArrayList<>();
for (CustomClass customClassValue: customClass) {
List<CustomClass> one = new ArrayList<>(), two = new ArrayList<>(), three = new ArrayList<>(), four = new ArrayList<>();
switch (customClassValue.getAge()){
case 1:
one.add(customClassValue);
break;
case 2:
two.add(customClassValue);
break;
case 3:
three.add(customClassValue);
break;
case 4:
four.add(customClassValue);
break;
}
returnValue.add(one);
returnValue.add(two);
returnValue.add(three);
returnValue.add(four);
}
return returnValue;
}
Is there any alternative in java collection than usage of List<List<CustomClass>>
in perspective of effectiveness and performance.
Simply to describe what the function does:
Takes a input of List of custom objects and categorizes them based on a field in object and returns each category item separately.
Upvotes: 0
Views: 92
Reputation:
Try this.
public List<List<CustomClass>> categorize(List<CustomClass> customClass) {
return customClass.stream()
.filter(v -> v.getAge() >= 1 && v.getAge() <= 4)
.collect(
() -> IntStream.range(0, 4)
.mapToObj(i -> new ArrayList<CustomClass>())
.collect(Collectors.toList()),
(list, v) -> list.get(v.getAge() - 1).add(v),
(a, b) -> {});
}
Upvotes: 0
Reputation: 582
A Multimap is a cleaner version of a Map<Key, List<Value>>
and Google's Guava has a nice implementation of it. It should solve the problem you have.
Upvotes: 0
Reputation: 54194
When you want to sort things into buckets, my first instinct is to use Map
instead of List
. Dividing a List<CustomClass>
into sublists based on age seems like a perfect time to use Map<Integer, List<CustomClass>>
. Here's one way to do that:
public Map<Integer, List<CustomClass>> categorize(List<CustomClass> customClass) {
Map<Integer, List<CustomClass>> returnValue = new HashMap<>();
for (CustomClass customClassValue: customClass) {
List<CustomClass> sublist = returnValue.get(customClassValue.getAge());
if (sublist == null) {
sublist = new ArrayList<>();
returnValue.put(customClassValue.getAge(), sublist);
}
sublist.add(customClassValue);
}
return returnValue;
}
Upvotes: 2