在实体集合中查找所有 id 集合的最有效方法 [英] Most efficient way to find the collection of all ids in a collection of entities
问题描述
我有一个实体:
public class Entity
{
private long id;
private String data;
public long getId() {
return id;
}
public String getData() {
return data;
}
}
和实体集合:
Collection<Entity> entities= ...
找到entities
中所有id的Collection
的最有效方法是什么?
What is the most efficient way to find the Collection<Long>
of all the ids in entities
?
推荐答案
假设你有
class Entity {
final long id;
final String data;
public long getId() {
return id;
}
public String getData() {
return data;
}
Entity(long id, String data) {
this.id = id;
this.data = data;
}
}
在 Java 8 中你可以编写
In Java 8 you can write
Collection<Entity> entities = Arrays.asList(new Entity(1, "one"),
new Entity(11, "eleven"), new Entity(100, "one hundred"));
// get a collection of all the ids.
List<Long> ids = entities.stream()
.map(Entity::getId).collect(Collectors.toList());
System.out.println(ids);
印刷品
[1, 10, 100]
你可以想象这在 Java 7 或更低版本中相当丑陋.注意 Entity.getId
当应用于 map() 意味着在每个元素上调用这个方法.
As you can imagine this is rather ugly in Java 7 or less. Note the Entity.getId
when applied to map() means call this method on each element.
现在,真正有趣的是你可以做到这一点.
Now, the real interesting part is you can do this.
List<Long> ids = entities.parallelStream()
.map(Entity::getId).collect(Collectors.toList());
在大多数情况使用并行流会影响性能,但它使尝试和看到非常容易(可能太容易了;)
In most cases using a parallel stream will hurt performance, but it makes trying it and seeing amazingly easy (possibly too easy ;)
最有效的方法是拥有或构建地图.
The most efficient way is to have, or build a Map.
Map<Long, Entity> entitiesMap = ...
// get all ids
Collection<Long> addIds = entitiesMap.keySet();
// look up entities by id.
List<Long> ids = ...
List<Entity> matching = new ArrayList<>();
for(Long id: ids)
matching.add(entitiesMap.get(id));
这篇关于在实体集合中查找所有 id 集合的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!