是否存在与c#abstract KeyedCollection类具有相同行为的Java集合(即可以通过键和索引检索项目)?我环顾四周但找不到类似的东西。
谢谢, 尼克
答案 0 :(得分:1)
我认为您可以通过扩展HashMap来开发自己的类
答案 1 :(得分:0)
我认为我能想到的最接近你想要的是树形图(http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html),但是你不能只通过键来索引项目。
答案 2 :(得分:0)
给出一个Entity
类:
@Data // lombok.Data, to have getters and setters
public class Entity {
private String myIndexingProperty;
// Other fields here
}
尝试实现类似于C#的KeyedCollection<T>
的方法是(Java 8 +):
import com.my.application.model.Entity;
import java.util.*;
import java.util.stream.Collectors;
public final class EntityMap implements Map<String, Entity> {
private TreeSet<Entity> set;
public EntityMap() {
set = new TreeSet<>();
}
@Override
public int size() {
return set.size();
}
@Override
public boolean isEmpty() {
return set.isEmpty();
}
@Override
public boolean containsKey(Object o) {
return set.stream()
.anyMatch(e -> String.valueOf(o).equalsIgnoreCase(e.getMyIndexingProperty()));
}
@Override
public boolean containsValue(Object o) {
return set.stream()
.anyMatch(e -> String.valueOf(o).equalsIgnoreCase(e.getMyIndexingProperty()));
}
@Override
public Entity get(Object o) {
return set.stream()
.filter(e -> String.valueOf(o).equalsIgnoreCase(e.getMyIndexingProperty()))
.findFirst()
.orElse(null);
}
@Override
public Entity put(String s, Entity entity) {
set.add(entity);
return set.stream()
.filter(e -> String.valueOf(entity.getMyIndexingProperty()).equalsIgnoreCase(e.getMyIndexingProperty()))
.findFirst()
.orElse(null);
}
@Override
public Verb remove(Object o) {
boolean removed = set.removeIf(e -> e.equals(o));
if (!removed) {
return null;
}
return get(o);
}
@Override
public void putAll(Map<? extends String, ? extends Entity> map) {
map.forEach(this::put);
}
@Override
public void clear() {
set.clear();
}
@Override
public Set<String> keySet() {
return set.stream()
.map(Entity::getMyIndexingProperty)
.collect(Collectors.toSet());
}
@Override
public Collection<Entity> values() {
return set;
}
@Override
public Set<Entry<String, Entity>> entrySet() {
return set.stream()
.map(e -> new AbstractMap.SimpleEntry<>(e.getMyIndexingProperty(), e))
.collect(Collectors.toSet());
}
}