JDK8lambda表达式之map和FlatMap区别

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo1 {

	public static void main(String[] args) {
		User user1 = new User(1, "u1", "shenyang", "hahaha");
		User user2 = new User(2, "u2", "shenyang", "gaga");
		User user3 = new User(3, "u3", "shanghai", "lala");
		User user4 = new User(4, "u4", "shanghai", "hahaha");
		User user5 = new User(5, "u5", "shenyang", "gaga");
		User user6 = new User(6, "u6", "shanghai", "hahaha");
		User user7 = new User(7, "u7", "beijing", "gaga");
		User user8 = new User(8, "u8", "beijing", "hahaha");
		User user9 = new User(9, "u9", "shenyang", "lala");
		List lis = new ArrayList<>();
		lis.add(user1);
		lis.add(user2);
		lis.add(user3);
		lis.add(user4);
		lis.add(user5);
		lis.add(user6);
		lis.add(user7);
		lis.add(user8);
		lis.add(user9);
		
		//List lis1 =lis.stream().filter(a->a.getAdd().equals("shenyang")).collect(Collectors.toList());
		//lis1.forEach(a->System.out.println(UserOp.getInfo(a)));
		
		int numcount =lis.stream().mapToInt(a->a.getNum()).sum();
		System.out.println(numcount);
		
		List aa=lis.stream().map(a->UserOp.getname(a)).collect(Collectors.toList());
		aa.forEach(a->System.out.println(a));
	}

}
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo3 {

	public static void main(String[] args) {
		User user1 = new User(1, "u1", "shenyang", "hahaha");
		User user2 = new User(2, "u2", "shenyang", "gaga");
		User user3 = new User(3, "u3", "shanghai", "lala");
		User user4 = new User(4, "u4", "shanghai", "hahaha");
		User user5 = new User(5, "u5", "shenyang", "gaga");
		User user6 = new User(6, "u6", "shanghai", "hahaha");
		User user7 = new User(7, "u7", "beijing", "gaga");
		User user8 = new User(8, "u8", "beijing", "hahaha");
		User user9 = new User(9, "u9", "shenyang", "lala");
		List lis = new ArrayList<>();
		lis.add(user1);
		lis.add(user2);
		lis.add(user3);
		lis.add(user4);
		List lis2 = new ArrayList<>();
		lis2.add(user5);
		lis2.add(user6);
		lis2.add(user7);
		lis2.add(user8);
		lis2.add(user9);
		
		List figures = Stream.of(lis, lis2).flatMap(u -> u.subList(0, 1).stream()).collect(Collectors.toList());
		figures.forEach(f -> System.out.println(f.getName()));
	}

}

通过以上示例代码,很容易发现其实map主要是用于遍历每个参数,然后进行参数合并或者返回新类型的集合。

FlatMap主要是用于stream合并,这个功能非常实用,他是默认实现多CPU并行执行的,所以我们合并集合优先实用这种方式。

你可能感兴趣的:(java)