博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java8 学习记录
阅读量:7153 次
发布时间:2019-06-29

本文共 7631 字,大约阅读时间需要 25 分钟。

  hot3.png

  • removeIf(Predicate<? super E> filter):移除集合中满足给定条件的所有元素,错误或者运行时异常发生在迭代时或者把条件传递给调用者的时候。
public static void main(String[] args) {    List
list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.removeIf(s -> s%2==0); // 过滤掉模2等于0的数 list.forEach(s -> System.out.println(s)); // 输出 1 3 List
strings = new ArrayList<>(); strings.add("ab"); strings.add("ac"); strings.add("bc"); strings.add("cd"); Predicate
predicate = (s) -> s.startsWith("a"); // 这里单独定义了过滤器 strings.removeIf(predicate); // 过滤掉以"a"开头的元素 strings.forEach(s -> System.out.println(s)); // 输出 bc cd}

forEach()

ArrayList
list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));list.forEach( str -> { if(str.length()>3) System.out.println(str); });

replaceAll()

ArrayList
list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));list.replaceAll(str -> { if(str.length()>3) return str.toUpperCase(); return str;});

sort()

ArrayList
list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));list.sort((str1, str2) -> str1.length()-str2.length());

spliterator()

这里输入代码

stream()

这里输入代码

parallelStream()

这里输入代码

Map中的新方法

forEach()

public Map
changeStatus(Map
map, Integer num, String str1, String str2) { Map
mapTwo = new HashMap<>(); map.forEach((k,v) ->{ if(v>num){ mapTwo.put(k,str1); }else{ mapTwo.put(k,str2); } }); return mapTwo; }实例即 Map
mapTwo = new HashMap<>(); Map
map = new HashMap
(); map.put("a",10); map.put("b",15); map.put("c",25); map.put("d",30); map.forEach((k,v) -> { if(v>20){ mapTwo.put(k,"busy"); }else{ mapTwo.put(k,"no busy"); } }); System.out.println(mapTwo); }
  • getOrDefault()

该方法跟Lambda表达式没关系,但是很有用。方法签名为V getOrDefault(Object key, V defaultValue),作用是按照给定的key查询Map中对应的value,如果没有找到则返回defaultValue。使用该方法程序员可以省去查询指定键值是否存在的麻烦.

Map
map = new HashMap
(); map.put("a",10); map.put("b",15); map.put("c",25); map.put("d",30); System.out.println(map.getOrDefault("e", 0));
  • putIfAbsent()

该方法跟Lambda表达式没关系,但是很有用。方法签名为V putIfAbsent(K key, V value),作用是只有在不存在key值的映射或映射值为null时,才将value指定的值放入到Map中,否则不对Map做更改.该方法将条件判断和赋值合二为一,使用起来更加方便

Map
mapTwo = new HashMap<>(); Map
map = new HashMap
(); map.put("a",10); map.put("b",15); map.put("c",25); map.put("d",30); System.out.println(map.getOrDefault("e", 0)); System.out.println(map); map.putIfAbsent("d",50); System.out.println(map); }------------------------------------------------{a=10, b=15, c=25, d=30}{a=10, b=15, c=25, d=30}
  • remove()

我们都知道Map中有一个remove(Object key)方法,来根据指定key值删除Map中的映射关系;Java8新增了remove(Object key, Object value)方法,只有在当前Map中key正好映射到value时才删除该映射,否则什么也不做.

  • replace()

在Java7及以前,要想替换Map中的映射关系可通过put(K key, V value)方法实现,该方法总是会用新值替换原来的值.为了更精确的控制替换行为,Java8在Map中加入了两个replace()方法,分别如下: replace(K key, V value),只有在当前Map中key的映射存在时才用value去替换原来的值,否则什么也不做. replace(K key, V oldValue, V newValue),只有在当前Map中key的映射存在且等于oldValue时才用newValue去替换原来的值,否则什么也不做.

  • replaceAll()

该方法签名为replaceAll(BiFunction<? super K,? super V,? extends V> function),作用是对Map中的每个映射执行function指定的操作,并用function的执行结果替换原来的value,其中BiFunction是一个函数接口,里面有一个待实现方法R apply(T t, U u).不要被如此多的函数接口吓到,因为使用的时候根本不需要知道他们的名字.

需求:假设有一个数字到对应英文单词的Map,请将原来映射关系中的单词都转换成大写.

Java7以及之前经典的代码如下:

HashMap
map = new HashMap<>();map.put(1, "one");map.put(2, "two");map.put(3, "three");for(Map.Entry
entry : map.entrySet()){ entry.setValue(entry.getValue().toUpperCase());}
HashMap
map = new HashMap<>();map.put(1, "one");map.put(2, "two");map.put(3, "three");map.replaceAll((k, v) -> v.toUpperCase());
  • merge()

该方法签名为merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction),作用是:

如果Map中key对应的映射不存在或者为null,则将value(不能是null)关联到key上; 否则执行remappingFunction,如果执行结果非null则用该结果跟key关联,否则在Map中删除key的映射. 参数中BiFunction函数接口前面已经介绍过,里面有一个待实现方法R apply(T t, U u).

merge()方法虽然语义有些复杂,但该方法的用方式很明确,一个比较常见的场景是将新的错误信息拼接到原来的信息上,比如:

map.merge(key, newMsg, (v1, v2) -> v1+v2);compute()

该方法签名为compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction),作用是把remappingFunction的计算结果关联到key上,如果计算结果为null,则在Map中删除key的映射.

要实现上述merge()方法中错误信息拼接的例子,使用compute()代码如下:

map.compute(key, (k,v) -> v==null ? newMsg : v.concat(newMsg));computeIfAbsent()

该方法签名为V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction),作用是:只有在当前Map中不存在key值的映射或映射值为null时,才调用mappingFunction,并在mappingFunction执行结果非null时,将结果跟key关联.

Function是一个函数接口,里面有一个待实现方法R apply(T t).

computeIfAbsent()常用来对Map的某个key值建立初始化映射.比如我们要实现一个多值映射,Map的定义可能是Map<K,Set<V>>,要向Map中放入新值,可通过如下代码实现:

Map
> map = new HashMap<>();// Java7及以前的实现方式if(map.containsKey(1)){ map.get(1).add("one");}else{ Set
valueSet = new HashSet
(); valueSet.add("one"); map.put(1, valueSet);

}这里输入这里输入代码代码 // Java8的实现方式

map.computeIfAbsent(1, v -> new HashSet
()).add("yi");

使用computeIfAbsent()将条件判断和添加操作合二为一,使代码更加简洁.

  • computeIfPresent()

该方法签名为V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction),作用跟computeIfAbsent()相反,即,只有在当前Map中存在key值的映射且非null时,才调用remappingFunction,如果remappingFunction执行结果为null,则删除key的映射,否则使用该结果替换key原来的映射.

这个函数的功能跟如下代码是等效的:

// Java7及以前跟computeIfPresent()等效的代码if (map.get(key) != null) {    V oldValue = map.get(key);    V newValue = remappingFunction.apply(key, oldValue);    if (newValue != null)        map.put(key, newValue);    else        map.remove(key);    return newValue;}return null;
  • reduce 这个方法的主要作用是把 Stream 元素组合起来。它提供一个起始值(种子),然后依照运算规则(BinaryOperator),和前面 Stream 的第一个、第二个、第 n 个元素组合。从这个意义上说,字符串拼接、数值的 sum、min、max、average 都是特殊的 reduce。例如 Stream 的 sum 就相当于
Integer sum = integers.reduce(0, (a, b) -> a+b); 或Integer sum = integers.reduce(0, Integer::sum);

也有没有起始值的情况,这时会把 Stream 的前面两个元素组合起来,返回的是 Optional。

// 字符串连接,concat = "ABCD"String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat); // 求最小值,minValue = -3.0double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min); // 求和,sumValue = 10, 有起始值int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);// 求和,sumValue = 10, 无起始值sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();// 过滤,字符串连接,concat = "ace"concat = Stream.of("a", "B", "c", "D", "e", "F"). filter(x -> x.compareTo("Z") > 0). reduce("", String::concat);

java8 四大核心函数式接口

Supplier<T>
定义函数示例:Supplier
supplier= () -> 100; // 常用于业务“有条件运行”时,符合条件再调用获取结果的应用场景;运行结果须提前定义,但不运行。调用函数示例:supplier.get();100

**Function<T, R> **:

T:入参类型,R:出参类型 调用方法:R apply(T t);

定义函数示例:Function
func = p -> p * 10; // 输出入参的10倍调用函数示例:func.apply(10); // 结果100
Consumer<T>

T:入参类型;没有出参 调用方法:void accept(T t);

定义函数示例:Consumer
consumer= p -> System.out.println(p); // 因为没有出参,常用于打印、发送短信等消费动作调用函数示例:consumer.accept("18800008888");
Predicate<T>

T:入参类型;出参类型是Boolean 调用方法:boolean test(T t);

定义函数示例:Predicate
predicate = p -> p % 2 == 0; // 判断是否、是不是偶数调用函数示例:predicate.test(100); // 运行结果true

将list或set转换为按行显示

每个字符串默认分隔符为空格,若需要指定分隔符,则在joining中加入参数即可:

String names = list.stream()                        .collect(Collectors.joining(", "));

转载于:https://my.oschina.net/112612/blog/1588810

你可能感兴趣的文章
2.编程语言,格式化输出,与用户交互
查看>>
hashlib加密
查看>>
又见拦截导弹
查看>>
CF978A Remove Duplicates【数组操作/STL】
查看>>
关于正则表达式-转载
查看>>
xml是什么?
查看>>
史上最简单的Docker入门教程
查看>>
对Spring的一些个人理解
查看>>
Builder设计模式
查看>>
深入浅出JVM
查看>>
第三次作业
查看>>
前端怎么学?
查看>>
centos7 安装php7
查看>>
Java并发编程:阻塞队列
查看>>
Construct Binary Tree from Inorder and Postorder Traversal
查看>>
USMT
查看>>
第二次作业
查看>>
是否是丑数
查看>>
txt1-txt2去重输出到txt3
查看>>
iOS 多线程
查看>>