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);`
相關文章
相關標籤/搜索