java8新特性中stream接口 distinct,sorted,peek,limit,skip reverse() 的用法

实例:

    /**
     * @param invoiceType 发票类型
     * @param reimburseStatus 发票状态
     * @param keyword 关键字
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param selectLable 标签
     * @param wtUid 委托人账号
     * @return
     */
    private Stream<InvoiceModel> getInvoiceModelStream(String invoiceType, String reimburseStatus, String keyword, String startTime, String endTime, String selectLable, String wtUid) {
        Stream<InvoiceModel> stream = null;
        if (UtilString.isNotEmpty(wtUid)) {
            stream = InvoiceCache.getCache().stream().filter(model -> wtUid.equals(model.getCreateUser())).filter(model -> model.getResultStatus().startsWith(InvoiceConstant.RESULT_STATUS_VALUE_SUCCESS) || model.getResultStatus().startsWith(InvoiceConstant.RESULT_STATUS_VALUE_SUCCESS_WX));//success or success_wx
        } else {
            stream = InvoiceCache.getCache().stream().filter(model -> getContext().getUID().equals(model.getCreateUser())).filter(model -> model.getResultStatus().startsWith(InvoiceConstant.RESULT_STATUS_VALUE_SUCCESS) || model.getResultStatus().startsWith(InvoiceConstant.RESULT_STATUS_VALUE_SUCCESS_WX));
        }
        if (UtilString.isNotEmpty(invoiceType)) {
            stream = stream.filter(model -> invoiceType.equals(model.getTicketType()));
        }
        if (UtilString.isNotEmpty(reimburseStatus)) {
            stream = stream.filter(model -> reimburseStatus.equals(model.getReimburseStatus()));
        }
        if (UtilString.isNotEmpty(selectLable)) {
            stream = stream.filter(invoiceModel -> {
                if (InvoiceConstant.TICKET_TYPE_INVOICE.equals(invoiceModel.getTicketType())) {
                    InvoiceTicketModel model = (InvoiceTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getLableName() != null && model.getLableName().contains(selectLable);
                    }
                } else if (InvoiceConstant.TICKET_TYPE_TRAIN.equals(invoiceModel.getTicketType())) {
                    TrainTicketModel model = (TrainTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getLableName() != null && model.getLableName().contains(selectLable);
                    }
                } else if (InvoiceConstant.TICKET_TYPE_PLANE.equals(invoiceModel.getTicketType())) {
                    AirTicketModel model = (AirTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getLableName() != null && model.getLableName().contains(selectLable);
                    }
                } else if (InvoiceConstant.TICKET_TYPE_MANUAL.equals(invoiceModel.getTicketType())) {
                    OtherTicketModel model = (OtherTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getLableName() != null && model.getLableName().contains(selectLable);
                    }
                }
                return false;
            });
        }

        if (UtilString.isNotEmpty(keyword)) {
            stream = stream.filter(invoiceModel -> {
                if (InvoiceConstant.TICKET_TYPE_INVOICE.equals(invoiceModel.getTicketType())) {
                    InvoiceTicketModel model = (InvoiceTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getSellerTaxName().contains(keyword) || model.getBuyerTaxName().contains(keyword)||model.getAmount().contains(keyword);
                    }
                } else if (InvoiceConstant.TICKET_TYPE_TRAIN.equals(invoiceModel.getTicketType())) {
                    TrainTicketModel model = (TrainTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getName().contains(keyword) || model.getStartLocation().contains(keyword) || model.getEndLocation().contains(keyword) || model.getTrainNumber().contains(keyword)||model.getAmount().contains(keyword);
                    }
                } else if (InvoiceConstant.TICKET_TYPE_PLANE.equals(invoiceModel.getTicketType())) {
                    AirTicketModel model = (AirTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getName().contains(keyword) || model.getStartLocation().contains(keyword) || model.getEndLocation().contains(keyword) || model.getFlightNumber().contains(keyword)||model.getAmount().contains(keyword);
                    }
                } else if (InvoiceConstant.TICKET_TYPE_MANUAL.equals(invoiceModel.getTicketType())) {
                    OtherTicketModel model = (OtherTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getMemo() != null && model.getMemo().contains(keyword)||model.getAmount().contains(keyword);
                    }
                }
                return false;
            });
        }
        if (UtilString.isNotEmpty(startTime)) {
            Timestamp startTimeTS = UtilDate.parseTsFromDateTime(startTime);
            stream = stream.filter(invoiceModel -> {
                if (InvoiceConstant.TICKET_TYPE_INVOICE.equals(invoiceModel.getTicketType())) {
                    InvoiceTicketModel model = (InvoiceTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getBillingDate().compareTo(startTimeTS) >= 0;
                    }
                } else if (InvoiceConstant.TICKET_TYPE_TRAIN.equals(invoiceModel.getTicketType())) {
                    TrainTicketModel model = (TrainTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getStartTime().compareTo(startTimeTS) >= 0 || model.getEndTime().compareTo(startTimeTS) >= 0;
                    }
                } else if (InvoiceConstant.TICKET_TYPE_PLANE.equals(invoiceModel.getTicketType())) {
                    AirTicketModel model = (AirTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getStartTime().compareTo(startTimeTS) >= 0 || model.getEndTime().compareTo(startTimeTS) >= 0;
                    }
                } else if (InvoiceConstant.TICKET_TYPE_MANUAL.equals(invoiceModel.getTicketType())) {
                    OtherTicketModel model = (OtherTicketModel) invoiceModel.getTicketModel();
                    if (model != null && model.getBillingDate() != null) {
                        return model.getBillingDate().compareTo(startTimeTS) >= 0;
                    }
                }
                return false;
            });
        }
        if (UtilString.isNotEmpty(endTime)) {
            Timestamp endTimeTS = UtilDate.parseTsFromDateTime(endTime);
            stream = stream.filter(invoiceModel -> {
                if (InvoiceConstant.TICKET_TYPE_INVOICE.equals(invoiceModel.getTicketType())) {
                    InvoiceTicketModel model = (InvoiceTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getBillingDate().compareTo(endTimeTS) <= 0;
                    }
                } else if (InvoiceConstant.TICKET_TYPE_TRAIN.equals(invoiceModel.getTicketType())) {
                    TrainTicketModel model = (TrainTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getStartTime().compareTo(endTimeTS) <= 0 || model.getEndTime().compareTo(endTimeTS) <= 0;
                    }
                } else if (InvoiceConstant.TICKET_TYPE_PLANE.equals(invoiceModel.getTicketType())) {
                    AirTicketModel model = (AirTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getStartTime().compareTo(endTimeTS) <= 0 || model.getEndTime().compareTo(endTimeTS) <= 0;
                    }
                } else if (InvoiceConstant.TICKET_TYPE_MANUAL.equals(invoiceModel.getTicketType())) {
                    OtherTicketModel model = (OtherTicketModel) invoiceModel.getTicketModel();
                    if (model != null) {
                        return model.getBillingDate().compareTo(endTimeTS) <= 0;
                    }
                }
                return false;
            });
        }
        stream = stream.distinct().sorted(Comparator.comparing(InvoiceModel::getCreateTime).reversed());
        return stream;
    }

 

    /**
     * 查询发票列表
     *
     * @param skip 跳过的条数
     * @param rowCount 此页查询的条数
     * @param invoiceType 发票类型
     * @param keyword 模糊搜索时的关键词
     * @param startTime 发票时间的范围 - 开始
     * @param endTime 发票时间的范围 - 结束
     * @param selectLable 发票名称
     * @param wtUid 委托人账号
     * @return
     */
    public String querySuccessInvoiceList(int skip, int rowCount, String invoiceType, String reimburseStatus, String keyword, String startTime, String endTime, String selectLable, String wtUid) {
        ResponseObject ro = ResponseObject.newOkResponse();
        try {
            Stream<InvoiceModel> stream1 = getInvoiceModelStream(invoiceType, reimburseStatus, keyword, startTime, endTime, selectLable, wtUid);
            Stream<InvoiceModel> stream3 = getInvoiceModelStream(invoiceType, reimburseStatus, keyword, startTime, endTime, selectLable, wtUid);

            List<InvoiceModel> list = stream1.skip(skip).limit(rowCount).collect(Collectors.toList());
            if (skip == 0) {//第一页需要查询总金额和总张数
                final int[] count = { 0 };
                double sum = stream3.mapToDouble(invoiceModel -> {
                    if (InvoiceConstant.TICKET_TYPE_INVOICE.equals(invoiceModel.getTicketType())) {
                        InvoiceTicketModel model = (InvoiceTicketModel) invoiceModel.getTicketModel();
                        if (model != null) {
                            count[0]++;
                            return Double.parseDouble(model.getAmount());
                        }
                    } else if (InvoiceConstant.TICKET_TYPE_TRAIN.equals(invoiceModel.getTicketType())) {
                        TrainTicketModel model = (TrainTicketModel) invoiceModel.getTicketModel();
                        if (model != null) {
                            count[0]++;
                            return Double.parseDouble(model.getAmount());
                        }
                    } else if (InvoiceConstant.TICKET_TYPE_PLANE.equals(invoiceModel.getTicketType())) {
                        AirTicketModel model = (AirTicketModel) invoiceModel.getTicketModel();
                        if (model != null) {
                            count[0]++;
                            return Double.parseDouble(model.getAmount());
                        }
                    } else if (InvoiceConstant.TICKET_TYPE_MANUAL.equals(invoiceModel.getTicketType())) {
                        OtherTicketModel model = (OtherTicketModel) invoiceModel.getTicketModel();
                        if (model != null) {
                            count[0]++;
                            return Double.parseDouble(model.getAmount());
                        }
                    }
                    return 0;
                }).sum();
                ro.put("sum", String.format("%.2f", sum));
                ro.put("count", count[0]);
            }
            JSONArray ja = getInvoiceJA(list);
            ro.put("list", ja);
            return ro.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("查询出错").toString();
        }
    }
View Code

 

 

//去重复

Stream<T> distinct();

//排序

Stream<T> sorted();

//根据属性排序

Stream<T> sorted(Comparator<? super T> comparator);

//对对象的进行操作

Stream<T> peek(Consumer<? super T> action);

//截断--取先maxSize个对象

Stream<T> limit(long maxSize);

//截断--忽略前N个对象

Stream<T> skip(long n);

下面,我们用一些案例,对这些操作,做一些综合的演示


 
package com.taihao;

 
import java.util.ArrayList;

import java.util.Arrays;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Stream;

 
public class TestJava8 {

public static List<Emp> list = new ArrayList<>();

static {

list.add(new Emp("xiaoHong1", 20, 1000.0));

list.add(new Emp("xiaoHong2", 25, 2000.0));

list.add(new Emp("xiaoHong3", 30, 3000.0));

list.add(new Emp("xiaoHong4", 35, 4000.0));

list.add(new Emp("xiaoHong5", 38, 5000.0));

list.add(new Emp("xiaoHong6", 45, 9000.0));

list.add(new Emp("xiaoHong7", 55, 10000.0));

list.add(new Emp("xiaoHong8", 42, 15000.0));

}

 
public static void println(Stream<Emp> stream) {

stream.forEach(emp -> {

System.out.println(String.format("名字:%s,年纪:%s,薪水:%s", emp.getName(), emp.getAge(), emp.getSalary()));

});

}

 
public static void main(String[] args) {

// 对数组流,先过滤重复,在排序,再控制台输出 1,2,3

Arrays.asList(3, 1, 2, 1).stream().distinct().sorted().forEach(str -> {

System.out.println(str);

});

// 对list里的emp对象,取出薪水,并对薪水进行排序,然后输出薪水的内容,map操作,改变了Strenm的泛型对象

list.stream().map(emp -> emp.getSalary()).sorted().forEach(salary -> {

System.out.println(salary);

});

// 根据emp的属性name,进行排序

println(list.stream().sorted(Comparator.comparing(Emp::getName)));

 
// 给年纪大于30岁的人,薪水提升1.5倍,并输出结果

Stream<Emp> stream = list.stream().filter(emp -> {

return emp.getAge() > 30;

}).peek(emp -> {

emp.setSalary(emp.getSalary() * 1.5);

});

println(stream);

// 数字从1开始迭代(无限流),下一个数字,是上个数字+1,忽略前5个 ,并且只取10个数字

// 原本1-无限,忽略前5个,就是1-5数字,不要,从6开始,截取10个,就是6-15

Stream.iterate(1, x -> ++x).skip(5).limit(10).forEach(System.out::println);

}

 
public static class Emp {

private String name;

 
private Integer age;

 
private Double salary;

 
public Emp(String name, Integer age, Double salary) {

super();

this.name = name;

this.age = age;

this.salary = salary;

}

 
public String getName() {

return name;

}

 
public void setName(String name) {

this.name = name;

}

 
public Integer getAge() {

return age;

}

 
public void setAge(Integer age) {

this.age = age;

}

 
public Double getSalary() {

return salary;

}

 
public void setSalary(Double salary) {

this.salary = salary;

}

 
}

}
View Code

 

reverse()

是python中列表的一个内置方法(也就是说,在字典,字符串或者元组中,是没有这个内置方法的),用于列表中数据的反转;

exp:

lista = [1, 2, 3, 4]

lista.reverse()

print(lista)

打印结果:

[4, 3, 2, 1]

  1. //去重复

  2. Stream<T> distinct();

  3. //排序

  4. Stream<T> sorted();

  5. //根据属性排序

  6. Stream<T> sorted(Comparator<? super T> comparator);

  7. //对对象的进行操作

  8. Stream<T> peek(Consumer<? super T> action);

  9. //截断--取先maxSize个对象

  10. Stream<T> limit(long maxSize);

  11. //截断--忽略前N个对象

  12. Stream<T> skip(long n);

下面,我们用一些案例,对这些操作,做一些综合的演示

 
  1. package com.taihao;

  2.  
  3. import java.util.ArrayList;

  4. import java.util.Arrays;

  5. import java.util.Comparator;

  6. import java.util.List;

  7. import java.util.stream.Stream;

  8.  
  9. public class TestJava8 {

  10. public static List<Emp> list = new ArrayList<>();

  11. static {

  12. list.add(new Emp("xiaoHong1", 20, 1000.0));

  13. list.add(new Emp("xiaoHong2", 25, 2000.0));

  14. list.add(new Emp("xiaoHong3", 30, 3000.0));

  15. list.add(new Emp("xiaoHong4", 35, 4000.0));

  16. list.add(new Emp("xiaoHong5", 38, 5000.0));

  17. list.add(new Emp("xiaoHong6", 45, 9000.0));

  18. list.add(new Emp("xiaoHong7", 55, 10000.0));

  19. list.add(new Emp("xiaoHong8", 42, 15000.0));

  20. }

  21.  
  22. public static void println(Stream<Emp> stream) {

  23. stream.forEach(emp -> {

  24. System.out.println(String.format("名字:%s,年纪:%s,薪水:%s", emp.getName(), emp.getAge(), emp.getSalary()));

  25. });

  26. }

  27.  
  28. public static void main(String[] args) {

  29. // 对数组流,先过滤重复,在排序,再控制台输出 1,2,3

  30. Arrays.asList(3, 1, 2, 1).stream().distinct().sorted().forEach(str -> {

  31. System.out.println(str);

  32. });

  33. // 对list里的emp对象,取出薪水,并对薪水进行排序,然后输出薪水的内容,map操作,改变了Strenm的泛型对象

  34. list.stream().map(emp -> emp.getSalary()).sorted().forEach(salary -> {

  35. System.out.println(salary);

  36. });

  37. // 根据emp的属性name,进行排序

  38. println(list.stream().sorted(Comparator.comparing(Emp::getName)));

  39.  
  40. // 给年纪大于30岁的人,薪水提升1.5倍,并输出结果

  41. Stream<Emp> stream = list.stream().filter(emp -> {

  42. return emp.getAge() > 30;

  43. }).peek(emp -> {

  44. emp.setSalary(emp.getSalary() * 1.5);

  45. });

  46. println(stream);

  47. // 数字从1开始迭代(无限流),下一个数字,是上个数字+1,忽略前5个 ,并且只取10个数字

  48. // 原本1-无限,忽略前5个,就是1-5数字,不要,从6开始,截取10个,就是6-15

  49. Stream.iterate(1, x -> ++x).skip(5).limit(10).forEach(System.out::println);

  50. }

  51.  
  52. public static class Emp {

  53. private String name;

  54.  
  55. private Integer age;

  56.  
  57. private Double salary;

  58.  
  59. public Emp(String name, Integer age, Double salary) {

  60. super();

  61. this.name = name;

  62. this.age = age;

  63. this.salary = salary;

  64. }

  65.  
  66. public String getName() {

  67. return name;

  68. }

  69.  
  70. public void setName(String name) {

  71. this.name = name;

  72. }

  73.  
  74. public Integer getAge() {

  75. return age;

  76. }

  77.  
  78. public void setAge(Integer age) {

  79. this.age = age;

  80. }

  81.  
  82. public Double getSalary() {

  83. return salary;

  84. }

  85.  
  86. public void setSalary(Double salary) {

  87. this.salary = salary;

  88. }

  89.  
  90. }

  91. }

posted @ 2020-02-19 23:51  R_Oasis  阅读(340)  评论(0编辑  收藏  举报