lambda表达式学习(三)

1.方法引用
方法引用是结合Lambda表达式的一种语法特性 分为以下几种引用
1.静态方法引用
类名称::方法名称
2.实例方法引用
对象应用::实例方法名称
3.构造方法引用
接口对象::new
测试类

package com.example.lambda.gwh;

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

/**
 * 方法引用
 * 1.静态方法的引用
 * (旧)类名称.方法名称 --->(新) 类名称::方法名称
 * 2.实例方法的引用
 * 创建类型对应的一个对象 -->对象应用::实例方法名称
 */
public class Test1 {
    public static void main(String[] args) {
        //添加对象到集合
        List<Person> personList=new ArrayList<>();
        personList.add(new Person("tom",16,"男"));
        personList.add(new Person("kangkang",16,"男"));
        personList.add(new Person("jerm",15,"女"));
        personList.add(new Person("anla",14,"女"));
        personList.add(new Person("wangzha",40,"男"));
        personList.add(new Person("zhuxiaoming",28,"男"));
        //实现排序 根据年龄
//        //1.匿名内部类
//        Collections.sort(personList, new Comparator<Person>() {
//            @Override
//            public int compare(Person o1, Person o2) {
//                return o1.getAge()-o2.getAge();
//            }
//        });
//        System.out.println(personList);
         //2.lambda表达式
      //  Collections.sort(personList,(p1,p2) -> p1.getAge()-p2.getAge());
       // System.out.println(personList);
      //3.引用静态方法 类名::方法名
      //  Collections.sort(personList,Person::compareByAge);
        //4.实例方法引用  对象名::方法名
//        PersonUtil pu =new PersonUtil();
//        Collections.sort(personList,pu::compareByName);
//        System.out.println(personList);
       //5.构造方法引用
        Iperson ip=Person::new;
        Person person=ip.initPerson("lilong",24,"男");
        System.out.println(person);

    }

}
interface  Iperson{
    //抽象方法:通过指定类型的构造方法初始化对象数据
    public Person initPerson(String name,int age,String sex);

}

class PersonUtil{

    public int compareByName(Person p1,Person p2){
        return p1.getName().hashCode()-p2.getName().hashCode();
    }

}

class  Person{

    private String name;
    private int age;
    private String sex;

    public Person() {
        super();
    }
    public Person(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    //静态方法
    public  static int compareByAge(Person p1,Person p2){
        return p1.getAge()-p2.getAge();
    }


    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

Stream的作用?
Stream API是JDK8新添加的处理集合的关键组件,提供了多种的函数式操作。
引入全新的Stream API。这里的流Stream和I/O流不同,它更像具有Iterable的集合类,但行为和集合类又有所不同。
Stream是对集合对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者打批量数据操作。
只要给出需要对其包含的元素执行什么操作,比如“过滤掉长度大于10的字符串”、“获取每个字符串的首字母”等,Stream会隐式地在内部进行遍历,做出相应的数据转换。
Java有关List的stream基本操作
Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象。
这种风格将要处理的元素集合看作一种流,流在管道中传输,并且可以在管道的节点上进行处理,比如筛选、排序、聚合等。
和以前的collection操作不同,Stream操作还有两个基础的特征:
Pipelining:中间操作都会返回流对象本身。这样多个操作可以串联成一个管道,如同流式风格。这样做可以对操作进行优化,比如延迟执行和短路。
内部迭代:以前对集合遍历都是通过Iterator或者ForEach的方式,显示的在集合外部进行迭代,这叫做外部迭代。Stream提供了内部迭代的方式,通过访问者模式实现。
一些方法:
stream();为集合创建串行流。
parallelStream(),为集合创建并行流。是流并行处理程序的代替方法。
forEach(),Stream提供的新的方法来迭代流中的每个数据。
map(),方法用于映射每个元素到对应的结果。map(i -> i*i)集合中的每个元素变为平方
filter(),方法用于通过设置的条件过滤出元素,filter(string -> string.isEmpty()) 过滤出空字符串。
limit(),方法用于获取指定数量的流。limit(10) 获取10条数据
sorted(),方法用于对流进行排序。
collect(Collectors.toList()),用于返回列表或字符串,Collectors.joining(",");将集合转换成逗号隔开的字符串
测试类

package com.example.lambda.gwh;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 简单理解Stream
 */
public class Test2 {

    public static void main(String[] args) {
        List<String> accounts=new ArrayList<String>();
        accounts.add("zhuxiaoming");
        accounts.add("wangzha");
        accounts.add("tom");
        accounts.add("try");
        accounts.add("doct");
        //1.1业务要求:长度大于等于5的有效账号
        for (String s :accounts){
            if(s.length()>=5){
                System.out.println(String.format("有效账号:%s",s));
            }
        }
        //1.2使用迭代器实现
        Iterator it=accounts.iterator();
        while (it.hasNext()){
            String account=(String) it.next();
            if(account.length()>=5){
                System.out.println(String.format("有效账号:%s",account));
            }
        }
        //1.3使用stream
        List<String> accountList=accounts.stream().filter(s ->s.length()>=5).collect(Collectors.toList());
        System.out.println(accountList);

    }

}

常用api

package com.example.lambda.gwh;

import javax.swing.text.html.Option;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * stream常见操作API
 * 1.聚合操作
 *
 * 2.stream的处理流程
 * 数据源
 * 数据转换
 * 获取结果
 * 3.获取stream对象
 * 1.从集合或者数组中获取
 *    Collection.stream()
 *    Collection.parallelstrem()
 *    Arrays.stream(T t)
 *  2.BufferReader
 *     BufferReader.lines() -> stream()
 *  3.静态工厂
 *
 */
public class Test3 {

    public static void main(String[] args) {
        //1.批量数据 -> Stream对象
        //多个数据 Stream.of
        Stream stream = Stream.of("admin","tom","damu");
        //数组 Arrays.stream
        String[] strArrays=new String[]{"youyong","xiaqi"};
        Stream stream2= Arrays.stream(strArrays);

        //列表
        List<String> list=new ArrayList<>();
        list.add("少林");
        list.add("武当");
        list.add("崆峒");
        list.add("峨眉");
        list.add("青城");
        Stream stream3=list.stream();

        //集合
        Set<String> set=new HashSet<>();
        set.add("少林");
        set.add("崆峒");
        set.add("峨眉");
        set.add("武当");
        Stream stream4=set.stream();
        //MAP
        Map<String,String> map=new HashMap<>();
        map.put("tom","男");
        map.put("hanji","男");
        map.put("jimi","女");
        Stream stream5=map.entrySet().stream();

        //2.Stream对象对于基本类型的功能性封装
        //int/ long/double
//        IntStream.of(new int[]{10,20,30,40}).forEach(System.out::println);
//        IntStream.range(1,5).forEach(System.out::println);
//        IntStream.rangeClosed(1,5).forEach(System.out::println);
        //3.Stream 对象 -->转换的到指定的数据类型
        //数组
 //       Object[] objx=stream.toArray(String[]::new);

        //字符串 根据指定字符进行拼接 stream进行完操作以后就会清空所以注释操作
        //String str=stream.collect(Collectors.joining(",")).toString();
        //System.out.println(str);

        //列表
        //List<String> listx=(List<String>) stream.collect(Collectors.toList());
        //System.out.println(listx);

        //集合
       // Set<String> setx=(Set<String>)stream.collect(Collectors.toSet());
        //System.out.println(setx);
        //Map
//        Map<String,String> mapx=(Map<String,String>)stream.collect(Collectors.toMap(x->x,y->"value:"+y));
//        System.out.println(mapx);
   //4.stream中常见的API操作
        List<String> accountList=new ArrayList<>();
        accountList.add("linchong");
        accountList.add("luzhishen");
        accountList.add("wusong");
        accountList.add("likui");
        accountList.add("songjiang");
        accountList.add("wuyong");
        accountList.add("shiqian");

        //map 对于map的简单操作
        //accountList=accountList.stream().map(x -> "name:"+x).collect(Collectors.toList());

        //过滤
        //accountList=accountList.stream().filter(x->x.length()>5).collect(Collectors.toList());
       // accountList.forEach(System.out::println);

        //forEach 增强型循环
//        accountList.forEach(x->System.out.println("foreach->"+x));
//        accountList.forEach(x->System.out.println("foreach->"+x));
//        accountList.forEach(x->System.out.println("foreach->"+x));
        //peek() 中间操作,迭代数据完成数据的依次处理过程
//        accountList.stream().peek(x -> System.out.println("peek 1:"+x))
//                               .peek(x->System.out.println("peek 2:"+x))
//                                .forEach(System.out::println);

        //stream 对数字的支持
        List<Integer> intList=new ArrayList<>();
        intList.add(22);
        intList.add(221);
        intList.add(22);
        intList.add(22);
        intList.add(22);
        intList.add(2);
        intList.add(21);
        intList.add(42);
        intList.add(22);
        intList.add(8);
        //skip() 中间操作,有状态,跳过部分数据
       // intList.stream().skip(6).forEach(System.out::println);
        // limit() 中间操作, 有状态, 限制输出条数
       // intList.stream().limit(2).forEach(System.out::println);
        //distinct() 中间操作, 有状态, 剔除重复的数据
        //intList.stream().distinct().forEach(System.out::println);
        //sorted() 中间操作, 有状态, 排序
        //intList.stream().sorted().forEach(System.out::println);
        //max() 获取最大值
        Optional optional=intList.stream().max((x, y)->x-y);
        System.out.println(optional.get());
        //min() 获取最小值
        Optional optional1=intList.stream().min((x,y)->x-y);
        System.out.println(optional1.get());
        //reduce() 合并处理
        Optional optional2=intList.stream().reduce((sum,x) -> sum+x);
        System.out.println(optional2.get());

    }


}

lambda表达式性能测试

package com.example.lambda.gwh;

import java.util.*;

/**
 * lambda表达式性能测试
 */
public class Test4 {
    public static void main(String[] args) {
        Random random=new Random();
        //1.基本数据类型:整数
        List<Integer> integerList=new ArrayList<>();
        for (int i =0;i<10000000;i++){
            integerList.add(random.nextInt(Integer.MAX_VALUE));
        }
//        //1.stream
//        testStream(integerList);
//        //2.parallelstream
//        testParallelStream(integerList);
//        //3.普通for
//      testforloop(integerList);
//        //4.增强型for
//      testStrongForloop(integerList);
//        //5.迭代器
//      testIterator(integerList);
        //2.复杂数据类型对象
        List<product> productList=new ArrayList<>();
        for (int i=0;i<100000;i++){
            productList.add(new product("pro"+i,i,random.nextInt(Integer.MAX_VALUE)));
        }
        //调用执行
        testProductStream(productList);
        testProductParallelStream(productList);
        testProductforloop(productList);
        testProductStrongForloop(productList);
        testProductIterator(productList);
    }
    public static void testStream(List<Integer> list){
        long start=System.currentTimeMillis();
        Optional optional=list.stream().max((x,y)->x-y);
        System.out.println(optional.get());
        long end=System.currentTimeMillis();
        System.out.println("testStream:"+(end-start)+"ms");

    }
    public static void testParallelStream(List<Integer> list){
        long start=System.currentTimeMillis();
        Optional optional=list.parallelStream().max((x,y)->x-y);
        System.out.println(optional.get());
        long end=System.currentTimeMillis();
        System.out.println("testParallelStream:"+(end-start)+"ms");

    }
    public static void testforloop(List<Integer> list){
        long start=System.currentTimeMillis();
        int max=Integer.MIN_VALUE;
        for (int i = 0;i<list.size();i++){
            int current = list.get(i);
            if (max<current){
                max=current;
            }
        }
        System.out.println(max);
        long end=System.currentTimeMillis();
        System.out.println("testforloop:"+(end-start)+"ms");

    }
    public static void testStrongForloop(List<Integer> list){
        long start=System.currentTimeMillis();
         int max=Integer.MIN_VALUE;
          for (Integer i :list){
              if(i>max){
                  max=i;
              }
          }
        System.out.println(max);
        long end=System.currentTimeMillis();
        System.out.println("testStrongForloop:"+(end-start)+"ms");

    }
    public static void testIterator(List<Integer> list){
        long start=System.currentTimeMillis();
        Iterator<Integer> it=list.iterator();
        int max=it.next();
        while (it.hasNext()){
            if(max<it.next()){
                max=it.next();
            }
        }
        System.out.println(max);
        long end=System.currentTimeMillis();
        System.out.println("testIterator:"+(end-start)+"ms");

    }

 static  class  product{
        String name; //名称
        Integer stock; //库存
        Integer hot; //热度

        public product() {
            super();
        }

        public product(String name, Integer stock, Integer hot) {
            this.name = name;
            this.stock = stock;
            this.hot = hot;
        }

        public String getName() {
            return name;
        }

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

        public Integer getStock() {
            return stock;
        }

        public void setStock(Integer stock) {
            this.stock = stock;
        }

        public Integer getHot() {
            return hot;
        }

        public void setHot(Integer hot) {
            this.hot = hot;
        }
    }

    public static void testProductStream(List<product> list){
        long start=System.currentTimeMillis();
        Optional optional=list.stream().max((p1,p2)->p1.getHot()-p2.getHot());
        System.out.println(optional.get());
        long end=System.currentTimeMillis();
        System.out.println("testProductStream:"+(end-start)+"ms");

    }
    public static void testProductParallelStream(List<product> list){
        long start=System.currentTimeMillis();
        Optional optional=list.parallelStream().max((p1,p2)->p1.getHot()-p2.getHot());
        System.out.println(optional.get());
        long end=System.currentTimeMillis();
        System.out.println("testProductParallelStream:"+(end-start)+"ms");

    }
    public static void testProductforloop(List<product> list){
        long start=System.currentTimeMillis();
        int max=list.get(0).getHot();
        for (int i = 0;i<list.size();i++){
            int current = list.get(i).getHot();
            if (max<current){
                max=current;
            }
        }
        System.out.println(max);
        long end=System.currentTimeMillis();
        System.out.println("testProductforloop:"+(end-start)+"ms");

    }
    public static void testProductStrongForloop(List<product> list){
        long start=System.currentTimeMillis();
        Integer max=list.get(0).getHot();
        for (product i :list){
            if(i.getHot()>max){
                max=i.getHot();
            }
        }
        System.out.println(max);
        long end=System.currentTimeMillis();
        System.out.println("testProductStrongForloop:"+(end-start)+"ms");

    }
    public static void testProductIterator(List<product> list){
        long start=System.currentTimeMillis();
        Iterator<product> it=list.iterator();
        int max=it.next().getHot();
        while (it.hasNext()){
            if(max<it.next().getHot()){
                max=it.next().getHot();
            }
        }
        System.out.println(max);
        long end=System.currentTimeMillis();
        System.out.println("testProductIterator:"+(end-start)+"ms");

    }


}

性能安全问题

package com.example.lambda.gwh;

import ch.qos.logback.core.net.SyslogOutputStream;
import org.hibernate.validator.constraints.SafeHtml;

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

/**
 * 性能安全问题
 */
public class Test5 {

    public static void main(String[] args) {

        List<Integer> lists=new ArrayList<>();
        for (int i=0;i<1000;i++){
            lists.add(i);
        }

        //串行stream
        List<Integer> list2=new ArrayList<>();
        lists.stream().forEach(x->list2.add(x));
        System.out.println(lists.size());
        System.out.println(list2.size());
        //并行stream 线程不安全,会造成数据丢失或者内存溢出
        List<Integer> list3=new ArrayList<>();
        lists.parallelStream().forEach(x->list3.add(x));
        System.out.println(list3.size());

        //解决并行stream 数据丢失问题
        List<Integer> list4=lists.parallelStream().collect(Collectors.toList());
        System.out.println(list4.size());

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值