org.aksw.commons.collections.ConvertingCollection Maven / Gradle / Ivy
package org.aksw.commons.collections;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import com.google.common.base.Converter;
public class ConvertingCollection>
extends AbstractCollection
{
protected C backend;
protected Converter converter;
public ConvertingCollection(C backend, Converter converter) {
// Objects.requireNonNull(backend);
// Objects.requireNonNull(converter);
this.backend = backend;
this.converter = converter;
}
public C getBackend() {
return backend;
}
@Override
public boolean add(F value) {
B item = converter.reverse().convert(value);
boolean result = backend.add(item);
return result;
}
@Override
public boolean remove(Object o) {
boolean result;
try {
@SuppressWarnings("unchecked")
B item = converter.reverse().convert((F)o);
result = backend.remove(item);
} catch(ClassCastException e) {
result = false;
}
return result;
}
@Override
public boolean contains(Object o) {
boolean result;
try {
@SuppressWarnings("unchecked")
B item = converter.reverse().convert((F)o);
result = backend.contains(item);
} catch(ClassCastException e) {
result = false;
}
return result;
}
@Override
public Iterator iterator() {
Iterator baseIt = backend.iterator();
Iterator result = new ConvertingIterator<>(baseIt, converter);
return result;
}
@Override
public int size() {
return backend.size();
}
/**
* Wraps the backend with a guava filteredCollection that filters out
* items for which the converter raises an exception
*
* @param
* @param
* @param
* @param backend
* @param converter
* @return
*/
public static > Collection createSafe(Collection backend, Converter converter) {
Collection safeBackend = MutableCollectionViews.filteringCollection(backend, converter);
Collection result = new ConvertingCollection<>(safeBackend, converter);
return result;
}
public static Stream convertRaw(Collection> c, Converter, O> converter) {
@SuppressWarnings("rawtypes")
Converter raw = converter;
Stream itemStream = c.stream().flatMap(item -> {
Stream r;
try {
@SuppressWarnings("unchecked")
O b = (O)raw.convert(item);
r = Stream.of(b);
} catch (ClassCastException e) {
r = Stream.empty();
}
return r;
})
.map(x -> (O)x);
return itemStream;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy