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"]
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With