rap*_*apt 21 java collections apache-commons guava
我有一个实体:
public class Entity
{
private long id;
private String data;
public long getId() {
return id;
}
public String getData() {
return data;
}
}
Run Code Online (Sandbox Code Playgroud)
和一组实体:
Collection<Entity> entities= ...
Run Code Online (Sandbox Code Playgroud)
找到Collection<Long>
所有ID 的最有效方法是什么entities
?
Pet*_*rey 42
假设你有
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在Java 8中,您可以编写
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);
Run Code Online (Sandbox Code Playgroud)
版画
[1, 10, 100]
Run Code Online (Sandbox Code Playgroud)
你可以想象这在Java 7或更低版本中相当丑陋.注意,Entity.getId
当应用于map()时,意味着在每个元素上调用此方法.
现在,真正有趣的部分是你可以做到这一点.
List<Long> ids = entities.parallelStream()
.map(Entity::getId).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,使用并行流会损害性能,但它会尝试它并且看起来非常简单(可能太简单了;)
最有效的方法是拥有或构建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));
Run Code Online (Sandbox Code Playgroud)
效率最高?基本上只是迭代并添加到列表中。您必须查看每个项目。
Collection<Long> ids = new LinkedList<Long>();
for (Entity e : entities) {
ids.add(e.id);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您可以使用 Java 1.8,您可以执行以下操作:
entities.forEach((e) -> ids.add(e.id));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41570 次 |
最近记录: |