Ümit
Ümit

Reputation: 17499

Iterate over an ImmutableSet and ImmutableList and mutate objects

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:

  1. Can I safely mutate a field of an object that is part of an immutable collection while I am iterating over it ?
  2. When I am iterating over the 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

Answers (1)

JB Nizet
JB Nizet

Reputation: 692231

  1. Yes, unless the double value is used to compute the hashCode of the entity, and the collection uses the hashCode. But I really don't see why you're using a Set here, and why it needs to be immutable. Just using new ArrayList<>(entity.getEntities()) would suffice to have a reliable, consistent iteration order.
  2. Yes, since the javadoc of ImmutableSet says: A high-performance, immutable Set with reliable, user-specified iteration order.

Upvotes: 3

Related Questions