按属性过滤对象列表并在java中生成属性列表

n91*_*915 5 java list filter

说我有一个对象

@AllArgsConstructor
class Foo {
 String name;
 int age;
}

public static void main() {
  List<Foo> fooList = new ArrayList<Foo>();
  ... populate list...
  List<String> filteredByName = getFilteredList(fooList);
}

public List<String> getFilteredList(List<Foo> fooList) {
  List<String> nameList = new ArrayList<String>();
  for(Foo foo : fooList) {
     if("someword".isGreaterThan(foo.getName()) {
        nameList.add(foo.getName());
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要 getFilteredList 的一行表示。Google Guava/ Apache 有谓词,可以将对象列表过滤为较小的列表,不确定是否有类似的东西可以单独过滤掉属性列表。

Jos*_*h M 10

如果您使用的是 Java 8,请使用流来过滤列表:

public List<String> getFilteredList(List<Foo> fooList) {
    return fooList.stream().filter(f -> "someword".compareTo(f.getName()) > 0))
                           .collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)