Reputation: 17499
I have following setup (i.e Entity
is a JPA2
entitiy and entities
is a collection)
class Entity {
Set<SubEntity> entities = new HashSet<>();
public Set<SubEntity> getEntities() {
return entities;
}
}
class SubEntity {
Double value;
// setters and getters ommitted
}
class SomeLibrary {
public static List<Double> transform(List<Double> values) {
// transform values and return a new list with transfored values
}
}
I need to transform the value
field in my SubEntity
by using an external library that takes a List<Doubles>
and returns a new list with the transformed values. Afterwards I need to update the SubEntity
with the transofmred value.
Because Set
does not guaranetee iteration order I first convert it to an ImmutableSet
and use Collections2.transform
to create an ImmutableList
of the values.
ImmutableSet<SubEntity> entities = ImmutableSet.copyOf(entity.getEntities());
ImmutableList<Double> values = ImmutableList.copyOf(Collections2.transform(entities, (e) -> e.getValue()))
At this point I assume that the items in both collections (entities
and values
match up, like when I zip both lists)
List<Double> transformedValues = SomeLibrary.transform(values);
Iterator<SubEntity> entityIterator = entities.iterator();
Iterator<Double> valueIterator = transformedValues.iterator();
while(entityIterator.hasNext() && valueIterator.hasNext()) {
SubEntity entity = entityIterator.next();
Double value = valueIterator.next();
entity.setValue(value);
}
So there are two questions:
ImmutableSet
of the SubEntity
and List
of transformed values, I assume that the values match up. Is this guaranteed when I am using immutable collections and the transform
function?Upvotes: 0
Views: 4974
Reputation: 692231
new ArrayList<>(entity.getEntities())
would suffice to have a reliable, consistent iteration order.Upvotes: 3