1

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 ?

1
  • 3
    Wouldn't ten binary values lead to 1024 permutations? You could collect this as bits (each field having its own bit), which could be directly used as a grouping index. Commented Jun 17, 2019 at 22:38

2 Answers 2

0

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

We cannot use 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 Collection
A BitSet 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.
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.