JAVA8 新特性StreamAPI使用

一、使用StreamAPI,操作两个队伍中名字,需求如下:

1、第一个队伍名字为3个字的成员姓名
2、第一个队伍筛选名字为3个字之后的前三个成员

3、第二个队伍筛选姓张的成员
4、第二个队伍筛选姓张的之后跳过前两个成员

5、将两个队伍合并成一个队伍
6、合并之后的队伍中的所有人的Person(自定义类型)对象,存储到一个List集合中。

 二、编码:

 2.1、原始数据 

public class TestStream3 {
    List<String> team1;
    List<String> team2;

    @Before
    public void load() {
        //原字符串
        String str1 = "宫本武藏、宋公明、苏有朋、石头人、时传祥、李耳、庄子、洪七公";
        String str2 = "帕瓦罗蒂、张山峰、赵薇薇、张自忠、铁木真、张天爱、张翠花";
        //分割字符串
        String[] strs1 = str1.split("、");
        String[] strs2 = str2.split("、");
        //存入集合中
        team1 = Arrays.asList(strs1);
        team2 = Arrays.asList(strs2);

        System.out.println(team1);
        System.out.println(team2);

    }


  
}

 2.2、自定义 Person类

public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

 2.3、 操作(1)和(2) 

    @Test
    public void test1() {
        //1、第一个队伍只要名字为3个字的成员姓名
        team1.stream().filter(i -> i.length() == 3).forEach(System.out::println);

        System.out.println("*****************************");
        //2、第一个队伍只要筛选名字为3个字之后的前三个人
        team1.stream().filter(i -> i.length() == 3).limit(3).forEach(System.out::println);
    }

2.4、操作(3)和(4)

 @Test
    public void test2() {
//        3、第二个队伍只要姓张的
        team2.stream().filter(i -> i.startsWith("张")).forEach(System.out::println);

        System.out.println("*****************************");
//        4、第二个队伍筛选之后不要前两个人
        team2.stream().filter(i -> i.startsWith("张")).skip(2).forEach(System.out::println);
    }

 

2.5、 操作(5)和(6)

 @Test
    public void test3() {
//        5、将两个队伍合并成一个队伍
        Stream.concat(team1.stream(),team2.stream()).forEach(System.out::println);

        System.out.println("*******************************");
//        6、合并之后的队伍中的所有人的Person(自定义类型)对象,存储到一个ArrayList集合中
        List<Person> pers=new ArrayList<>();
        Stream.concat(team1.stream(), team2.stream())
                .map(Person::new)   //映射每个对象
                .forEach(pers::add); //循环添加

        pers.stream().forEach(System.out::println);


    }

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值