VCollections.src.org.violetlib.collections.impl.SimpleOrderedSet Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vcollections Show documentation
Show all versions of vcollections Show documentation
Java Immutable Collections
The newest version!
/*
* Copyright (c) 2023 Alan Snyder.
* All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the license agreement. For details see
* accompanying license terms.
*/
package org.violetlib.collections.impl;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Function;
import org.violetlib.collections.ICollection;
import org.violetlib.collections.IIterator;
import org.violetlib.collections.IList;
import org.violetlib.collections.ISet;
import org.violetlib.collections.SetBuilder;
import org.jetbrains.annotations.*;
import static java.util.Spliterator.*;
/**
*/
public final class SimpleOrderedSet
implements ISet
{
public static @NotNull ISet create(@NotNull ISet members, @NotNull IList order)
{
return new SimpleOrderedSet<>(members, order);
}
public static @NotNull ISet create(@NotNull IList members)
{
return new SimpleOrderedSet<>(ISet.create(members), members);
}
private final @NotNull ISet members;
private final @NotNull IList order;
private SimpleOrderedSet(@NotNull ISet members, @NotNull IList order)
{
this.members = members;
this.order = order;
}
@Override
public int size()
{
return members.size();
}
@Override
public @NotNull ISet extending(@NotNull V value)
{
if (members.contains(value)) {
return this;
}
return new SimpleOrderedSet<>(members.extending(value), order.appending(value));
}
@Override
public @NotNull ISet extendingAll(@NotNull ICollection extends V> values)
{
ISet result = this;
for (V value : values) {
result = result.extending(value);
}
return result;
}
@Override
public @NotNull ISet removing(@NotNull Object value)
{
if (members.contains(value)) {
return new SimpleOrderedSet<>(members.removing(value), order.removing(value));
} else {
return this;
}
}
@Override
public @NotNull ISet map(@NotNull Function mapper)
{
SetBuilder b = ISet.builder();
for (V v : order) {
R mapped = mapper.apply(v);
b.addOptional(mapped);
}
return b.values();
}
@Override
public @NotNull IIterator iterator()
{
return order.iterator();
}
@Override
public @NotNull Spliterator spliterator()
{
return Spliterators.spliterator(iterator(), size(), IMMUTABLE | NONNULL | SIZED | DISTINCT);
}
}