如何在多条件下从流中收集
How to collect from streams on multi condition
List<Category> category = categoryRepository.findRootCategories(scope.getValue())
.map(Category::getMasterCategory)
.map(Category::getCode)
.filter(code -> code.equalsIgnoreCase(orderType))
.collect(Collectors.toList());
这有什么问题吗?
我收到编译错误。我想在两个条件
上过滤 findRootCategories
方法返回的类别
- 先拿到主分类
- 将master类别的代码与一些输入进行比较
错误:class 中的方法 collect 无法应用于给定类型;
执行此操作后 .map(Category::getCode)
流类型将是 return 类型的 getCode()
。假设 getCode()
return 字符串然后收集为列表它将 return List<String>
.
List<Category> category = categoryRepository
.findRootCategories(scope.getValue()) // Stream<Category>
.map(Category::getMasterCategory) // Stream<Category>
.map(Category::getCode) // Stream<String>
.filter(code -> code.equalsIgnoreCase(orderType)) // Stream<String>
.collect(Collectors.toList()); // List<String>
检查过滤器的条件不需要这样做 .map(Category::getCode)
。您可以直接检查过滤器内部(如@ernest_k 建议的那样),然后 Stream 类型保持 Category
List<Category> category = categoryRepository
.findRootCategories(scope.getValue()) // Stream<Category>
.map(Category::getMasterCategory) // Stream<Category>
.filter(category -> category.getCode()
.equalsIgnoreCase(orderType)) // Stream<Category>
.collect(Collectors.toList()); // List<Category>
List<Category> category = categoryRepository.findRootCategories(scope.getValue())
.map(Category::getMasterCategory)
.map(Category::getCode)
.filter(code -> code.equalsIgnoreCase(orderType))
.collect(Collectors.toList());
这有什么问题吗? 我收到编译错误。我想在两个条件
上过滤findRootCategories
方法返回的类别
- 先拿到主分类
- 将master类别的代码与一些输入进行比较
错误:class 中的方法 collect 无法应用于给定类型;
执行此操作后 .map(Category::getCode)
流类型将是 return 类型的 getCode()
。假设 getCode()
return 字符串然后收集为列表它将 return List<String>
.
List<Category> category = categoryRepository
.findRootCategories(scope.getValue()) // Stream<Category>
.map(Category::getMasterCategory) // Stream<Category>
.map(Category::getCode) // Stream<String>
.filter(code -> code.equalsIgnoreCase(orderType)) // Stream<String>
.collect(Collectors.toList()); // List<String>
检查过滤器的条件不需要这样做 .map(Category::getCode)
。您可以直接检查过滤器内部(如@ernest_k 建议的那样),然后 Stream 类型保持 Category
List<Category> category = categoryRepository
.findRootCategories(scope.getValue()) // Stream<Category>
.map(Category::getMasterCategory) // Stream<Category>
.filter(category -> category.getCode()
.equalsIgnoreCase(orderType)) // Stream<Category>
.collect(Collectors.toList()); // List<Category>