Search code examples
javacollectionscloneguavaimmutability

Create a deep copy of a Collection to a ImmutableSortedSet upon initialization of a class in java


I have an ImmutableSortedSet that is create on initialization of a class. For every object of this class i want the ImmutableSortedSet to have a deep copy (clone) of the elements stored in an Collection located in another file.

This is the collection with the original values (could also be a set)

public static final List<Quest> QUESTS = new ArrayList<>();

This is the class i want to create with the ImmutableSortedSet

package com.vencillio.rs2.content.quest;

import java.util.Optional;
import java.util.Set;

import com.google.common.collect.ImmutableSortedSet;

public class QuestManager {

    private int questPoints = 0;
    private final Set<Quest> QUESTS = ImmutableSortedSet.copyOf(Quest.QUESTS); //This is only a shallow copy

    public int getQuestPoints() {
        return questPoints;
    }

    public void addQuestPoints(int amount) {
        questPoints += amount;
    }

    public void removeQuestPoints(int amount) {
        questPoints -= amount;
    }

    public Optional<QuestState> getQuestState(String name) {
        return getQuest(name).isPresent() ? Optional.of(getQuest(name).get().getQuestState()) : Optional.empty();
    }

    public void setQuestState(String name, QuestState state) {
        if(getQuest(name).isPresent())
            getQuest(name).get().setQuestState(state);
    }

    public Optional<Quest> getQuest(String name) {
        return QUESTS.stream().filter(quest -> quest.getName().equalsIgnoreCase(name)).findAny();
    }
}

Solution

  • You haven't explained how to get a copy of a Quest in the first place, which is an aspect of your design. In general, I'd write something like

    import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
    import static java.util.Comparator.naturalOrder;
    
    Quest.QUESTS.stream()
       .map(quest -> copy(quest))
       .collect(toImmutableSortedSet(naturalOrder()));