Reputation: 1457
Imagine that we have a bean like this:
@Data
class MyBean{
private String name:
private String age;
private String gender;
...
}
And Another bean with order variables
@Data
class Order{
private String orderVariable;
private String orderValue;
}
I have a List of Order
[ "mygender","M"], ["myname", "Louis"],["myage", 12]...
[ "mygender","F"], ["myage", 13], ["myname", "Anna"]...
[ "myname", "Peter"], ["myage", 14], ["mygender","M"]...
I need to map both:
List<MyBean> myBeanList = new ArrayList<>();
for(Order order: ordersList){
MyBean myBean = new MyBean();
if(order.getOrderVariable().equals("myname")){
myBean.setname(order.orderValue());
}
else if(order.getOrderVariable().equals("mygender")){
myBean.setGender(order.orderValue());
}
else if(order.getOrderVariable().equals("myage")){
myBean.setAge(order.orderValue());
}
...
}
The problem is I have more than 20 variables in MyBean, so this is not the cleanest way. How can I do this?
Upvotes: 0
Views: 301
Reputation: 16775
What I suggest to do is create a hash map which maps each orderVariable
to a BiConsumer
. This consumer is basically holds lambdas to setter methods for every field from MyBean
.
This will look as follows:
Map<String, BiConsumer<Order, MyBean>> dispatch = new HashMap<String, BiConsumer<Order, MyBean>>() {{
put("myname", (order, myBean) -> myBean.setName(order.getOrderValue()));
put("mygender", (order, myBean) -> myBean.setGender(order.getOrderValue()));
put("myage", (order, myBean) -> myBean.setAge(order.getOrderValue()));
// Add other consumers for other fields
}};
for (Order order : orderList) {
MyBean myBean = new MyBean();
dispatch.getOrDefault(order.getOrderVariable(), (unusedOrder, unusedMyBean) -> {}).accept(order, myBean);
// Do something with myBean
}
Another approach would be the usage of reflection, although usually I don't really recommend it, since it can be pretty fragile and error prone.
public static void main(String[] args) throws IllegalAccessException {
for (Order order : orderList) {
MyBean myBean = new MyBean();
// Get all fields from MyBean
Field[] fields = myBean.getClass().getDeclaredFields();
for (Field field : fields) {
// Check if field name is similar to the orderVariable value from order.
if (order.getOrderVariable().contains(field.getName())) {
// Make field accessible to be editable by reflection.
field.setAccessible(true);
// set field value
field.set(myBean, order.getOrderValue());
// reset the accessibility of the field
field.setAccessible(false);
}
}
// Do something here
}
}
Upvotes: 1