Ven*_*nki 1 java collections guava
这是我的样本对象
public class Dummy {
private long id;
private String name;
/**
* @return the id.
*/
public long getId() {
return id;
}
/**
* @param id the id to set.
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the name.
*/
public String getName() {
return name;
}
/**
* @param name the name to set.
*/
public void setName(String name) {
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我有这些对象的列表,我需要获取列表中该对象中存在的ID列表.我可以轻松地做到这一点
List<Long> ids = Lists.newArrayList();
for(Dummy dummy: dummyList){
ids.add(dummy.getId());
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以通过使用替代方法(而不是使用for循环可能?)来完成,而不是我想出的可能正在使用Iterables或Collections过滤?
编辑:我有兴趣知道如何以不同于我想出的方式完成它.
您可以使用Iterables.transform获取指数的Iterable:
List<Dummy> dummyList = Lists.newArrayList();
Iterable<Long> idList = Iterables.transform(dummyList, new Function<Dummy, Long>() {
public Long apply(Dummy dummy) { return dummy.getId(); };
});
Run Code Online (Sandbox Code Playgroud)
但这似乎真的太过分了.你获得了一条线,你的可读性就会下降.
从Java 8开始,你已经关闭了,你可以用更简单的方式编写它.
List<Long> idList = dummyList
.stream()
.map(Dummy::getId)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)