com.jparams.store.index.References Maven / Gradle / Ivy
package com.jparams.store.index;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.jparams.store.index.reducer.Reducer;
import com.jparams.store.reference.Reference;
public class References
{
private final K key;
private final Reducer reducer;
private final Set> references;
private Set> reducedReferences;
private References(final K key, final Set> references, final Collection> reducedReferences, final Reducer reducer)
{
this.key = key;
this.references = new LinkedHashSet<>(references);
this.reducedReferences = new LinkedHashSet<>(reducedReferences);
this.reducer = reducer;
}
public References(final K key, final Reference reference, final Reducer reducer)
{
this(key, Collections.singleton(reference), Collections.emptySet(), reducer);
reducedReferences.add(reference);
reducedReferences = reduce(reducedReferences);
}
public void add(final Reference reference)
{
references.add(reference);
reducedReferences.add(reference);
reducedReferences = reduce(reducedReferences);
}
public void remove(final Reference reference)
{
references.remove(reference);
if (reducedReferences.contains(reference))
{
reducedReferences = reduce(references); // on remove, re-reduce all references associated with this key
}
}
public Set> getAllReferences()
{
return Collections.unmodifiableSet(reducedReferences);
}
public List getAll()
{
return reducedReferences.stream().map(Reference::get).collect(Collectors.toList());
}
public boolean isEmpty()
{
return references.isEmpty();
}
public Optional findFirst()
{
return reducedReferences.stream().map(Reference::get).findFirst();
}
public References copy()
{
return new References<>(key, references, reducedReferences, reducer);
}
private Set> reduce(final Set> references)
{
if (reducer == null)
{
return references;
}
final List> elements = references.stream().map(Element::new).collect(Collectors.toList());
reducer.reduce(key, elements);
return elements.stream()
.filter(element -> !element.isRemoved())
.map(Element::getReference)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy