java8 lambda表达式 map_JDK8lambda表达式之map和FlatMap区别

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:52   1994   0

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");

Listlis = 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);

//Listlis1 =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);

Listaa=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");

Listlis = new ArrayList<>();

lis.add(user1);

lis.add(user2);

lis.add(user3);

lis.add(user4);

Listlis2 = new ArrayList<>();

lis2.add(user5);

lis2.add(user6);

lis2.add(user7);

lis2.add(user8);

lis2.add(user9);

Listfigures = 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并行执行的,所以我们合并集合优先实用这种方式。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP