Jdk8 Streams API List 转化列子

ぃ、小莉子 提交于 2019-11-29 20:47:07

利用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);`
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!