Jdk8 Streams API List 转化列子

利用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";code

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);`
相关文章
相关标签/搜索