5

I am looking for a clean and elegant way to transform an object variables into an array based on the variable values.

Example:

public class Subject {

    public Subject(boolean music, boolean food, boolean sport, boolean business, boolean art) {
        this.music = music;
        this.food = food;
        this.sport = sport;
        this.business = business;
        this.art = art;
    }

    private final Long id;
    private final boolean music;
    private final boolean food;
    private final boolean sport;
    private final boolean business;
    private final boolean art;

}

Based on the values of each field, I want to add the field name as a string into an array.

Example: new Subject(true, true, true, false, false)

Expected result: ["music", "food", "sport"]

0

3 Answers 3

5

Assuming no getters, you can use reflection:

Subject subject = new Subject(true, true, true, false, false);

Field[] fields = Subject.class.getDeclaredFields();   // Get the object's fields
List<String> result = new ArrayList<>();
Object value;

for(Field field : fields) {                           // Iterate over the object's fields

    field.setAccessible(true);                        // Ignore the private modifier
    value = field.get(subject);                       // Get the value stored in the field

    if(value instanceof Boolean && (Boolean)value) {  // If this field contains a boolean object and the boolean is set to true
        result.add(field.getName());                  // Add the field name to the list
    }
}
System.out.println(result); // ["music", "food", "sport"]


Working example

Sign up to request clarification or add additional context in comments.

Comments

2

For a general solution you can use reflection and Java Streams for this:

Subject subject = new Subject(true, true, true, false, false);
String[] trueFields = Arrays.stream(subject.getClass().getDeclaredFields())
        .filter(f -> {
            f.setAccessible(true);
            try {
                return f.getBoolean(subject);
            } catch (IllegalAccessException e) {
                return false;
            }
        })
        .map(Field::getName)
        .toArray(String[]::new);

The result will be:

[music, food, sport]

Comments

2

You can use java's reflection to achieve this

 List<String> output =  new ArrayList<>();
    for(Field f:s.getClass().getDeclaredFields()) {
        if((f.getType().equals(boolean.class) || f.getType().equals(Boolean.class)) && f.getBoolean(s)) {
            output.add(f.getName());
        }
    }

    System.out.println(output);

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.