Estoy tratando de poner en práctica una lógica en la que tengo una clase POJO que tiene 7 atributos. He añadido estas clases POJO en el mapa depende del valor de los atributos.
A continuación se muestra la ejecución
Map<String,List<PriceClass>> map = new HashMap();
for (PriceClass price : prices) {
if (price.getAttribute1() !=null) {
if (map.get("attribute1") !=null) {
map.get("attribute1").add(price);
} else {
map.set("attibute1",Collections.singletonList(price))
}
} else if(price.getAttribute2()!=null) {
if (map.get("attribute12") !=null) {
map.get("attribute2").add(price);
} else {
map.set("attibute2",Collections.singletonList(price))
}
} else if (price.getAttribute3() !=null) {
.
.
.
} else if (price.getAttribute7() !=null) {
//update the map
}
}
Mi pregunta es en lugar de escribir estos bucles muchos, si hay alguna implementaciones Generalizar puedo probar aquí.
Una solución óptima sería probablemente similar a uno que he sugerido el día de hoy.
Utilice el Map<String, Optional<?>>
para almacenar los Optional
valores de los atributos controladas con una clave de la futura clave del mapa de salida.
Map<String, Optional<?>> options = new HashMap<>();
options.put("attribute1", Optional.ofNullable(price.getAttribute1()));
// ...
options.put("attribute3", Optional.ofNullable(price.getAttribute2()));
// ...
Usando la iteración de los índices dejaría de llevar a cabo la actualización de un mapa.
Map<String,List<Price>> map = new HashMap();
for (int i=1; i<7; i++) { // attributes 1..7
String attribute = "attribute" + i; // attribute1...attribute7
options.get(attribute).ifPresent(any -> // for non-nulls
map.put( // put to the map
attribute, // attribute as key remains
Optional.ofNullable(map.get(attribute)) // gets the existing list
.orElse(new ArrayList<>()) // or creates empty
.add(price))); // adds the current Price
}
Por otra parte, apuesto a que su intención era un poco diferente. No existe un métodoMap::set
map.set("attibute1",Collections.singletonList(price))
¿No te refieres a poner List<Price>
con un elemento de la misma clave en su lugar?
map.put("attibute1", Collections.singletonList(price))
Por esta razón, se puede utilizar la forma en que he publicado anteriormente.