java8函数式编程,常用高阶函数处理

jdk1.8引入了Lombda表达式,函数式编程,帮我大大减少了代码的重复性,和代码的复杂度,更优雅的处理我们代码和方法,也能帮我业务数据做处理。

函数接口:

函数接口指仅具有单个抽象方法的接口,用来表示 Lambda 表达式的类型。

是惰性求值还是及早求值很简单:只需看它的返回值。如果返回值是 Stream, 那么是惰性求值;如果返回值是另一个值或为空,那么就是及早求值。

通过构建建筑者模式构建数据:

package com.example.java8.employees;

import java.util.List;
import java.util.Objects;

/**
 * 使用建造者模式创建对象:
 * 1,对象在赋值过后进行bulider创建对象
 *2,多线程里面对象他是线程安全,类this指向
 * @author xpwi
 * @since 2022-08-14
 */
public class EmployeesVO {

    /**
     * id 编号
     */
    private int id;

    /**
     * 姓名
     */
    private String name;
    /**
     * 性别
     */
    private Integer gender;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 信息
     */
    private String msg;


    private List result;

    public EmployeesVO(Bulider bulider){
        this.id = bulider.id;
        this.name = bulider.name;
        this.age = bulider.age;
        this.gender = bulider.gender;
        this.msg = bulider.msg;
        this.result=bulider.result;

    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List getResult() {
        return result;
    }

    public void setResult(List result) {
        this.result = result;
    }

    /**
     * 工厂
     *
     */
    public  static class  Bulider{
        /**
         * id 编号
         */
        private int id;

        /**
         * 姓名
         */
        private String name;
        /**
         * 性别
         */
        private Integer gender;

        /**
         * 年龄
         */
        private Integer age;

        /**
         * 信息
         */
        private String msg;


        private List result;

        public Bulider(int id, String name, Integer gender, Integer age, String msg,List result) {
            this.id = id;
            this.name = name;
            this.gender = gender;
            this.age = age;
            this.msg = msg;
            this.result = result;
        }

        public Bulider id(int id){
            this.id=id;
            return this;
        }
        public Bulider name(String name){
            this.name=name;
            return this;
        }
        public Bulider name(Integer gender){
            this.gender=gender;
            return this;
        }
        public Bulider age(Integer age){
            this.age=gender;
            return this;
        }
        public Bulider age(String  msg){
            this.msg=msg;
            return this;
        }
        public Bulider result(List result){
            this.result=result;
            return this;
        }
        /**
         * this指向赋值this
         * @return
         */
        public EmployeesVO bulider(){
            return new EmployeesVO(this);
        }

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        EmployeesVO that = (EmployeesVO) o;
        return id == that.id &&
                Objects.equals(name, that.name) &&
                Objects.equals(gender, that.gender) &&
                Objects.equals(age, that.age) &&
                Objects.equals(msg, that.msg) &&
                Objects.equals(result, that.result);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, gender, age, msg, result);
    }
}

测试类:

package com.example.java8.employees;

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

/**
 * 

* * @author xpwi * @since 2022-08-14 */ public class TestJava8 { public static List oldList = new ArrayList<>(); public static List newList = new ArrayList<>(); static { initData(); } /** * 初始化数据 */ public static void initData() { List result= new ArrayList<>(); result.add("1d"); result.add("25"); result.add("3d"); List result2= new ArrayList<>(); result2.add("4d"); result2.add("55"); result2.add("6d"); EmployeesVO employeesVO1 = null; employeesVO1 = new EmployeesVO.Bulider(1, "王二", 0, 25, "test1",result).bulider(); oldList.add(employeesVO1); employeesVO1 = new EmployeesVO.Bulider(1, "王二", 0, 25, "test1",result).bulider(); oldList.add(employeesVO1); employeesVO1= new EmployeesVO.Bulider(1, "王二", 1, 25, "test1",result).bulider(); oldList.add(employeesVO1); employeesVO1 = new EmployeesVO.Bulider(4, "李慧", 1, 20, "test 4",result2).bulider(); oldList.add(employeesVO1); employeesVO1 = new EmployeesVO.Bulider(5, "王二三", 0, 25, "test 5",result2).bulider(); oldList.add(employeesVO1); List result4= new ArrayList<>(); result2.add("1f"); result2.add("e5"); result2.add("1h"); EmployeesVO employeesVO6 = new EmployeesVO.Bulider(6, "王二", 0, 25, "test 6",result2).bulider(); EmployeesVO employeesVO7 = new EmployeesVO.Bulider(7, "李二", 0, 25, "test 7",result4).bulider(); EmployeesVO employeesVO8 = new EmployeesVO.Bulider(8, "杨慧", 1, 23, "test 8",result4).bulider(); EmployeesVO employeesVO9 = new EmployeesVO.Bulider(9, "周慧", 1, 20, "test 8",result4).bulider(); EmployeesVO employeesVO10 = new EmployeesVO.Bulider(10, "周二", 0, 25, "test 10",result4).bulider(); newList.add(employeesVO6); newList.add(employeesVO7); newList.add(employeesVO8); newList.add(employeesVO9); newList.add(employeesVO10); } /** * java常用函数: * 1,filter 代码的if操作,过滤数据 * 2,map * 3,flatMap * 4,collect * 5,peek 调试 ,idea工具 * 6,noneMatch,anyMatch * 7,skip * 8,distinct * 9,收集器 分组,sql group by * 分组,过滤,求和,平均,多个流合并,集合并集,交集,差集,map,集合转换 * * @param args */ public static void main(String args[]) { //filter 操作 List result1 = oldList.stream().filter(employeesVO -> employeesVO.getName().equals("王二三")).collect(Collectors.toList()); //集合差集 根据前面的对象来的 List result2 = oldList.stream().filter(item-> !newList.stream().map( employees -> employees.getName() ).collect(Collectors.toList()).contains(item.getName())).collect(Collectors.toList()); //俩个对象相同的交集 List result3 = oldList.stream().filter(item->newList.stream().anyMatch( employeesVO -> Objects.equals(item.getName(),employeesVO.getName())) ).peek(employeesVO -> employeesVO.getGender()).collect(Collectors.toList()); //去重 List result4 = newList.stream().collect( Collectors.collectingAndThen(Collectors.toCollection( ()->new TreeSet<>(Comparator.comparing(o->o.getName()+":"+o.getId())) ),ArrayList::new)); //分页 // newList.stream().skip((i-1)*size).limit(size).collect(Collectors.toList()); //flatmap 合并流 List result5 = oldList.stream().map(m->m.getResult()).flatMap(Collection::stream).collect(Collectors.toList()); //gropuby 分组 Map > result6 = newList.stream().map(item->item).collect(Collectors.groupingBy(employeesVO -> employeesVO.getGender())); //收集器 Map > result7 = newList.stream().collect(Collectors.partitioningBy(employeesVO -> employeesVO.getGender()==0)); //distinct 去重 重写equeas 和hash方法 List result8 = oldList.stream().distinct().collect(Collectors.toList()); //map集合 EmployeesVO employeesVO = new EmployeesVO.Bulider(6, "缓存", 0, 25, "缓存",null).bulider(); cache.put("缓存",employeesVO); TestJava8 testJava8 = new TestJava8(); EmployeesVO employeesVO1 =testJava8.getEmpCache("缓存222"); EmployeesVO employeesVO3 =testJava8.getEmpCache("缓存222"); System.out.println(result2); } public static Map cache = new HashMap<>(); public EmployeesVO employeesVO(String name){ EmployeesVO employeesVO = new EmployeesVO.Bulider(6, "缓存", 0, 25, "缓存",null).bulider(); return employeesVO; } public EmployeesVO getEmpCache(String name){ return cache.computeIfAbsent(name,this::employeesVO); } }

filter 操作

相对循环里面的if

List beginningWithNumbers = new ArrayList<>();

for(String value : asList("a", "1abc", "abc1")) {

if (isDigit(value.charAt(0))) {

beginningWithNumbers.add(value);

}

}

assertEquals(asList("1abc"), beginningWithNumbers);

flatMap 操作(多个流合并成一个流)

一个对象的集合合并为一个对象

List result = newList.stream().map(m->m.getResult()).flatMap(Collection::stream).collect(Collectors.toList());

java8分页

list.stream().skip((i - 1) * sheetSize).limit(sheetSize). collect(Collectors.toList());

List newList2 = newList.stream().skip(( 1-1)* 2).limit(2).collect(Collectors.toList());
List newList3 = newList.stream().skip(( 2 -1)*2).limit(2).collect(Collectors.toList());
List newList4= newList.stream().skip(( 3 -1)*2).limit(2).collect(Collectors.toList());

java8 集合取差集

List result3 = newList.stream().filter(item-> !oldList.stream().map(
employees -> employees.getName()
).collect(Collectors.toList()).contains(item.getName())).collect(Collectors.toList());

java8根据参数过滤

result2.stream().filter(m->m.getVehicleNo().equals(parms.get(0))).collect(Collectors.toList());

java8集合对象多个值去重:

newList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
()-> new TreeSet<>(Comparator.comparing(o -> o.getName()+":"+o.getId()))
), ArrayIter::new));

java8取俩个对象相同的属性的值:

List result= oldList.stream().filter(item->newList.stream().anyMatch(employees -> Objects.equals(employees.name, item.name))).collect(Collectors.toList());

java8取前面个一个对象不相同的属性的值:


List result= oldList.stream().filter(item->newList.stream().noneMatch(employees -> Objects.equals(employees.name, item.name))).collect(Collectors.toList());

收集器:partitioningBy


Map> map = newList.stream().collect(Collectors.partitioningBy(employDO -> 0==employDO.getGender()));

groupingBy 收集器
SQL 中的 group by 操作

Map > resultFlter = newList.stream().map(m->m).collect(Collectors.groupingBy(employees -> employees.getName()));

map集合函数:computeIfAbsent

static Map artistCache = new HashMap<>();

public Employees getAuthCenterVo(String unionId){
Employees newEmployees = new Employees();
newEmployees.setId(1222);
newEmployees.setName("22222");
newEmployees.setAge(2222);
newEmployees.setGender(2222);
return newEmployees;
}
public Employees getlist(String name) {
return artistCache.computeIfAbsent(name, this::getAuthCenterVo);
}

调试解决方案:peak

记录日志这是 peek 方法的用途之一。为了像调试循环那样一步一步跟踪,可在 peek 方法 中加入断点,这样就能逐个调试流中的元素了。 此时,peek 方法可知包含一个空的方法体,只要能设置断点就行。有一些调试器不允许在 空的方法体中设置断点,此时,我将值简单地映射为其本身,这样就有地方设置断点了, 虽然这样做不够完美,但只要能工作就行

断点到方法调试

peek方法

示列1:

List result = newList.stream().peek(
m->System.out.println(m)
).collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(
o->o.getName()+":"+o.getGender()))
),ArrayList::new ));

示列2:
long wordsList = Arrays.stream(test22.split(",")).map(m->m ).peek( t->System.out.println(t)).filter(textContent::equals)
.count();

idea调试

java8函数式编程,常用高阶函数处理_第1张图片

常用的java8函数表达式就基本差不多这么多了,如果你需要了解其他的高阶的函数,可以去用@FuctionInterface注解操作

你可能感兴趣的:(java服务,java,servlet,前端)