编程语言
首页 > 编程语言> > Java 8 新特性

Java 8 新特性

作者:互联网

Java 8 新特性

Lambda 表达式

函数式编程,所有功能就是返回一个新的值,没有其他行为,尤其是不得修改外部变量的值。

简单demo如下

import java.util.ArrayList;
import java.util.List;

public class StreamDemo {
    public static void main(String[] args) {
        List<String> firstList = new ArrayList<>();
        firstList.add("1");
        //实现接口
        TestOperation testOperation = (list) -> {
            list.add("2");
        };
        //调用接口的operation方法
        testOperation.operation(firstList);
        //打印firstList
        firstList.forEach(System.out::println);
    }
    //定义一个接口
    interface TestOperation {
        void operation(List<String> list);
    }
}

Stream

stream()方法为集合创建串行流。

filter

filter 方法用于通过设置的条件过滤出元素

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "", "def", "ghi", "jkl", "mno"));
    List<String> secondList = stringList.stream().filter(string -> {
        //过滤空字符串
        if(string.isEmpty()){
            return false;
        }
        return true;
    }).collect(Collectors.toList());
    //更简便的语句
    //List<String> secondList = stringList.stream().filter(string->!string.isEmpty()).collect(Collectors.toList());
    //打印字符串
    secondList.forEach(System.out::println);
}

forEach

Stream 提供了新的方法 ‘forEach’ 来迭代流中的每个数据

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "", "def", "ghi", "jkl", "mno"));
    List<String> secondList = new ArrayList<>(stringList);
    //foreach
    secondList.forEach(str->{
        if(!str.isEmpty()){
            System.out.println("str "+str+" is not empty!");
        }else {
            System.out.println("it has a empty string!");
        }
    });
}

limit

limit 方法用于获取指定数量的流

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "", "def", "ghi", "jkl", "mno"));
    List<String> secondList = stringList.stream().filter(string->!string.isEmpty()).limit(2).collect(Collectors.toList());
    secondList.forEach(System.out::println);
}

map

map 方法用于映射每个元素到对应的结果

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "", "def", "ghi", "jkl", "mno"));
    List<String> secondList = stringList.stream().filter(string->!string.isEmpty()).map(str->{
        //该处map的作用就是处理原来的字符串,
        //然后返回处理结果替换原来的字符串,
        //这里只是模拟在原来字符串后加了","
        return str+",";
    }).collect(Collectors.toList());
    secondList.forEach(System.out::println);
}
public static void main(String[] args) {
    List<Integer> numberList = Arrays.asList(1, 2, 2, 3, 4, 5, 6, 7);
    // 获取对应的平方数,且采用distinct()方法过滤相同的平方数
    List<Integer> squaresList = numberList.stream().map( i -> i*i).distinct().collect(Collectors.toList());
    squaresList.forEach(System.out::println);
}

第二种方式,采用Collectors.toMap可以生成map返回,此处需要注意的是,如果list中有相同的值,需要加distinct()去除相同的值,因为如果采用map的话,像如下例子中,“abc"有两个,所以会报错"Duplicate key abc”,此处根据需要决定是否使用该方法生成map。

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "abc", "def", "ghi", "jkl", "mno"));
    Map<String, String> strMap;
    //list转map
    strMap = stringList.stream().filter(str->!str.isEmpty()).distinct().collect(Collectors.toMap(str->str, str->str));
    //遍历打印map
    strMap.forEach((key,value)->{
        System.out.println(key+"::"+value);
    });
}

distinct

过滤相同的元素

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "abc", "def", "ghi", "jkl", "mno"));
    List<String> secondList = stringList.stream().filter(string->!string.isEmpty()).distinct().collect(Collectors.toList());
    secondList.forEach(System.out::println);
}

sorted

sorted 方法用于对元素进行排序,默认是升序排列

public static void main(String[] args) {
    List<Integer> numberList = Arrays.asList(8, 5, 2, 3, 4, 7, 6, 1);
    List<Integer> secondNumList = numberList.stream().sorted().collect(Collectors.toList());
    secondNumList.forEach(System.out::println);
}

修改成降序排列

public static void main(String[] args) {
    List<Integer> numberList = Arrays.asList(8, 5, 2, 3, 4, 7, 6, 1);
    List<Integer> secondNumList = numberList.stream().sorted((x,y)->y-x).collect(Collectors.toList());
    secondNumList.forEach(System.out::println);
}

Collectors

Collectors 提供了一系列的操作,常用的有两个,一个是Collectors.toList(),将流转换成List,第二个是Collectors.joining(",")可以将流通过响应字符分割拼接成一个字符串

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>(Arrays.asList("abc", "abc", "def", "ghi", "jkl", "mno"));
    String secondStr = stringList.stream().filter(string->!string.isEmpty()).distinct().collect(Collectors.joining(","));
    System.out.println(secondStr);
}

Consumer接口

public class Goods {
    private int id;
    private int price;
    private String description;

    public int getId() {
        return id;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
public class ConsumerDemo {
    public static void main(String[] args) {
        Consumer<Goods> goodsConsumer = (goods -> {
            //对goods对象进行响应的业务处理
            goods.setDescription("test");
        });
        //在需要进行特殊处理的地方,传递goodsConsume作为参数即可
        //一般在公共方法中规定好一般的业务处理逻辑,然后传递Consumer
        //参数进去,在公共方法中判断其是否为空,不为空,则调用其accept方法进行特殊处理
        Goods goods = new Goods();
        goodsConsumer.accept(goods);

        System.out.println(goods.getDescription());
    }
}

标签:Java,String,Collectors,void,List,特性,stringList,public
来源: https://blog.csdn.net/qq_39871579/article/details/120605598