I have a class with 10 attributes. I want to group list of objects of that class based on attributes populated or not. Precisely I will get 2^n groups. I can iterate the list and write 2^n conditions and group them into new lists. Are there any other better ways to implement this functionality instead of writing those switch conditions ?
2 Answers
You can avoid writing multiple switch statements and have an identifier/key in the class itself which helps in understanding if certain properties are set or not.
Example:
DemoClass (3 attributes for simplification)
public class DemoClass {
public String property1 = null;
public String property2 = null;
public String property3 = null;
public String getKey() {
StringBuilder sb = new StringBuilder();
sb.append(this.property1 != null ? "PROPERTY1" : "").append("|");
sb.append(this.property2 != null ? "PROPERTY2" : "").append("|");
sb.append(this.property3 != null ? "PROPERTY3" : "").append("|");
return sb.toString();
}
}
Above the fields can be populated in various ways such as overloaded constructors or setter methods.
Now when you want to separate into groups, you can use a HashMap and add the objects of the class to the list based on the value of their keys as below
Map<String, List<DemoClass>> map = new HashMap<>();
for (DemoClass demoClass : demoClasses) {
map.computeIfAbsent(demoClass.getKey(), k -> new ArrayList<>()).add(demoClass);
}
2 Comments
demoClass instead as it is an instance of DemoClass and not of the HashMap. Also computeIfAbsent is a nice API provided by Java and it makes the code much easier to understand as compared to doing a getOrDefault which is useful if the value is not a CollectionBitSet can also be used but I felt that the above solution of having a String key which gives info about the set attributes is much more readable and can be extended further to use cases such as finding out which attributes are populated.I ended up getting a bit value of the attributes of the Record (1's and 0's for every attribute (1 means value exists and 0 means it does not exist)) in a string and grouped by them by String.
records.stream().map(record -> new ExportDto.Builder().buildUpon(record).bitValue(getBitValueOfExportRecord(record)).build())
.collect(Collectors.groupingBy(ExportDto::getBitValue))