利用Streams API List<Category> 转 List<CategoryTreeNode>
public List<CategoryTreeNode> findTreeList() {
List<CategoryTreeNode> tree = categoryRepository.findBySuperiorIdIsNull().stream()
.map(category -> new CategoryTreeNode(category.getCategoryName(), category.getCategoryId()))
.collect(Collectors.toList());
return tree;
}
集合内某字段相加
Set<ItemMetric> expenses = new HashSet<>();
BigDecimal b = new BigDecimal(100);
ItemMetric e = new ItemMetric("test", b);
expenses.add(e);
BigDecimal b1 = new BigDecimal(200);
ItemMetric e1 = new ItemMetric("aa", b1);
expenses.add(e1);
BigDecimal expensesAmount = expenses.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(expensesAmount);
多个stream组合使用 `String mobile = "19900505017";
List<String> cmcc = Arrays.asList("133", "135");
List<String> cucc = Arrays.asList("185", "186");
List<String> ctcc = Arrays.asList("133", "153");
String s1 = cmcc.stream().filter(t -> mobile.startsWith(t)).map(v -> "中国移动").findFirst()
.orElse(cucc.stream().filter(t -> mobile.startsWith(t)).map(v -> "中国联通").findFirst()
.orElse(ctcc.stream().filter(t -> mobile.startsWith(t)).map(v -> "中国电信").findFirst().orElse(UNFIND)));
System.out.println(s1);`
来源:oschina
链接:https://my.oschina.net/u/124056/blog/855767