java8系列之-使用lambda表达式对List集合进行操作

1.条件筛选

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;


public class LambdaStudy
{
    public static void main(String[] args) 
    {
       
        // 初始化list集合
        List list = new ArrayList();
        list.add("测试数据1");
        list.add("测试数据2");
        list.add("测试数据3");
        list.add("测试数据12");
        
        // 使用λ表达式遍历集合
        list.forEach(s -> System.out.println(s));
        
        // 结合Predicate使用和过滤条件筛选元素
        Predicate contain1 = n -> n.contains("1");
        Predicate contain2 = n -> n.contains("2");
        
        // 根据条件遍历集合
        list.stream().filter(contain1).forEach(n -> System.out.println(n));
        list.stream().filter(s -> contain1.test(s)).forEach(s -> System.out.println(s));
        list.stream().filter(contain1.and(contain2)).forEach(n -> System.out.println(n));
        list.stream().filter(contain1.or(contain2)).forEach(n -> System.out.println(n));
        
        // 将过滤后的元素重新放到一个集合中
        List newList = list.stream().filter(contain1.and(contain2)).collect(Collectors.toList());
        
        newList.forEach(s -> System.out.println(s));

    }
}

2.索引循环

package com.wc.list.test;

import com.wc.list.model.Model01;
import com.wc.list.model.Model02;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ListTest01
{
    public static void main(String[] args)
    {
        List model01s = new ArrayList()
        {{
            add(Model01.builder().code("1111").name("1111").build());
            add(Model01.builder().code("2222").name("2222").build());
            add(Model01.builder().code("3333").name("3333").build());
            add(Model01.builder().code("4444").name("4444").build());
        }};

        List model02s = new ArrayList()
        {{
            add(Model02.builder().code("5555").name("5555").build());
            add(Model02.builder().code("6666").name("6666").build());
            add(Model02.builder().code("7777").name("7777").build());
            add(Model02.builder().code("8888").name("9999").build());
        }};


        Stream.iterate(0, i -> i + 1).limit(model01s.size()).forEach(i ->
        {
            model02s.get(i).setCode(model01s.get(i).getCode());
        });

        log.info("model02s >>> {}", model02s);
    }
}
package com.wc.list.model;

import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Model01
{
    private String name;
    private String code;
}
package com.wc.list.model;

import lombok.*;


@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Model02
{
    private String name;
    private String code;
}
15:23:18.614 [main] INFO com.wc.list.test.ListTest01 - model02s >>> [Model02(name=5555, code=1111), Model02(name=6666, code=2222), Model02(name=7777, code=3333), Model02(name=9999, code=4444)]

 

你可能感兴趣的:(#,Java8,Java后台)