如何根据这些对象的属性从对象列表中提取值?

Nic*_*Div 2 java collections list

我想基于具有特定属性的列表中的对象.

例如,假设我有这个类的对象列表:

class Person {
    private String name;
    private String id;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用以下命令获取列表中所有人的名字:

Collection<String> names = CollectionUtils.collect(
    personList,
    TransformerUtils.invokerTransformer("getName"));  
Run Code Online (Sandbox Code Playgroud)

但我想要做的是获取一个Person名称对象的列表,例如"Nick".我没有Java 8.

Som*_*ude 6

我看到你正在使用Apache Common Utils,那么你可以使用:

CollectionUtils.filter( personList, new Predicate<Person>() {
    @Override
    public boolean evaluate( Person p ) {
        return p.getName() != null && p.getName().equals( "Nick" );
    }
});
Run Code Online (Sandbox Code Playgroud)

  • `return"Nick".equals(p.getName());` (3认同)