Java lambda 方法使用(1)

Java lambda 方法使用(1)


		
		ArrayList list = Lists.newArrayList("1","2","3","4","5");
		//打印元素
		list.stream().forEach(x ->{
			System.out.println(x);
		});
		
		//打印元素
		list.stream().forEach(System.out::println);
		
		//过滤元素
		List collect = list.stream()
				.filter(x -> Integer.valueOf(x) % 2 == 0)
				.collect(Collectors.toList());
		
		//判断元素是否满足预判条件,全部满足
		boolean allMatch = list.stream().allMatch(x -> Integer.valueOf(x) % 2 == 0);
		
		//判断元素是否满足预判条件,只要有一个满足
		boolean anyMatch = list.stream().anyMatch(x -> Integer.valueOf(x) % 2 == 0);
		
		//分组
		Map> collect2 = list.stream()
				.collect(Collectors.groupingBy(x -> Integer.valueOf(x) % 4));
		
		//特殊的,分成两组
		Map> collect3 = list.stream()
				.collect(Collectors.partitioningBy(x -> Integer.valueOf(x) % 2 == 0));
		
		//转Map
		Map collect4 = list.stream()
				.collect(Collectors.toMap(x -> "key" + x, x -> "value" + x));
		
		//指定返回集合
		TreeSet collect5 = list.stream()
				.collect(Collectors.toCollection(() -> new TreeSet()));
		
		//map转换
		List collect6 = list.stream().map(x -> Integer.valueOf(x)).collect(Collectors.toList());
		
		//mapToInt,并求和
		list.stream().mapToInt(new ToIntFunction() {
			@Override
			public int applyAsInt(String value) {
				return Integer.valueOf(value);
			}
		}).sum();
		
		//自定义收集器
		Supplier supplier = () -> new StringBuffer("");
		BiConsumer accumulator = (x,y) -> x.append(y);
		BiConsumer combiner = (x,y) -> x.append(y);
		StringBuffer collect7 = list.stream().collect(supplier , accumulator , combiner);
		
		
		
	

你可能感兴趣的:(java)