JDK 8 新特性- 学习中
目录
1. List Stream distinct() 去重
例子1
例子2
2 Streams filter() and collect()
3 Try后面跟括号
4 JDK8中有双冒号的用法
1. List Stream distinct() 去重
List Stream 对象调用distinct()方法,distinct()方法依赖hashCode()和equals()方法。
判断两个对象是否相同原理与HashMap定位key原理相同,先计算hashCode,如果hashCode相同继续调用equals()方法
例子1
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;public class Jdk8TestNew {public static void main(String[] args) {List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");long l = list.stream().distinct().count();System.out.println("No. of distinct elements:"+l);String output = list.stream().distinct().collect(Collectors.joining(","));System.out.println(output);}}
结果
No. of distinct elements:3
AA,BB,CC
例子2
加一下User class
public class User {private String username;private String password;public User(String username, String password) {super();this.username = username;this.password = password;}@Overridepublic int hashCode() {System.out.println(this+", hashCode method");final int prime = 31;int result = 1;result = prime * result + ((password == null) ? 0 : password.hashCode());result = prime * result + ((username == null) ? 0 : username.hashCode());return result;}@Overridepublic boolean equals(Object obj) {System.out.println(obj+", equals method");if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;User other = (User) obj;if (password == null) {if (other.password != null)return false;} else if (!password.equals(other.password))return false;if (username == null) {if (other.username != null)return false;} else if (!username.equals(other.username))return false;return true;}@Overridepublic String toString() {return "User [username=" + username + ", password=" + password + "]";}}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;public class Jdk8TestNew {public static void main(String[] args) {List<User> users = new ArrayList<>();users.add(new User("wangwang", "3"));users.add(new User("wangwang", "3"));users.add(new User("guagua", "2"));System.out.println(users.stream().distinct().collect(Collectors.toList()));}}
结果
User [username=wangwang, password=3], hashCode method
User [username=wangwang, password=3], hashCode method
User [username=wangwang, password=3], hashCode method
User [username=wangwang, password=3], equals method
User [username=guagua, password=2], hashCode method
User [username=guagua, password=2], hashCode method
[User [username=wangwang, password=3], User [username=guagua, password=2]]
2 Streams filter() and collect()
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;public class Jdk8TestNew {public static void main(String args[]) {List<String> lines = Arrays.asList("spring", "node", "mkyong");List<String> result0 = getFilterOutput(lines, "mkyong");// output "spring", "node"for (String temp : result0) {System.out.println(temp);}/* The equivalent example in Java 8, using stream.filter() tofilter a list, and collect() to convert a stream.*/List<String> result1 = lines.stream() // convert list to stream.filter(line -> !"mkyong".equals(line)) // filter the line which equals to "mkyong".collect(Collectors.toList()); // collect the output and convert streams to a listresult1.forEach(System.out::println); // output "spring", "node"}private static List<String> getFilterOutput(List<String> lines, String filter) {List<String> result = new ArrayList<>();for (String line : lines) {if (!"mkyong".equals(line)) {result.add(line);}}return result;}}
结果
spring
node
spring
node
3 Try后面跟括号
java7新特性,支持使用try后面跟()括号,用来管理释放资源,try括号内的资源会在try语句结束后自动释放,前提是这些课关闭的资源必须实现 java.lang.AutoCloseable接口
package com.download;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;public class WordCount {public static void main(String[] args) {try (InputStream in = new FileInputStream("");OutputStream out = new FileOutputStream("");){byte[] buf = new byte[8192];int i;while ((i = in.read(buf)) != -1) {out.write(buf, 0, i);}} catch (IOException e) {e.printStackTrace();}}
}
4 JDK8中有双冒号的用法
JDK8中有双冒号的用法,就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下。
代码
public class AcceptMethod {public static void printValur(String str){System.out.println("print value : "+str);}public static void main(String[] args) {List<String> al = Arrays.asList("a","b","c","d");for (String a: al) {AcceptMethod.printValur(a);}//下面的for each循环和上面的循环是等价的 al.forEach(x->{AcceptMethod.printValur(x);});}
}
现在JDK双冒号是:
public class MyTest {public static void printValur(String str){System.out.println("print value : "+str);}public static void main(String[] args) {List<String> al = Arrays.asList("a", "b", "c", "d");al.forEach(AcceptMethod::printValur);//下面的方法和上面等价的Consumer<String> methodParam = AcceptMethod::printValur; //方法参数al.forEach(x -> methodParam.accept(x));//方法执行accept}
}
上面的所有方法执行玩的结果都是如下:
print value : a
print value : b
print value : c
print value : d
在JDK8中,接口Iterable 8中默认实现了forEach方法,调用了 JDK8中增加的接口Consumer内的accept方法,执行传入的方法参数。
JDK源码如下:
/*** Performs the given action for each element of the {@code Iterable}* until all elements have been processed or the action throws an* exception. Unless otherwise specified by the implementing class,* actions are performed in the order of iteration (if an iteration order* is specified). Exceptions thrown by the action are relayed to the* caller.** @implSpec* <p>The default implementation behaves as if:* <pre>{@code* for (T t : this)* action.accept(t);* }</pre>** @param action The action to be performed for each element* @throws NullPointerException if the specified action is null* @since 1.8*/default void forEach(Consumer<? super T> action) {Objects.requireNonNull(action);for (T t : this) {action.accept(t);}}
另外补充一下,JDK8改动的,在接口里面可以有默认实现,就是在接口前加上default,实现这个接口的函数对于默认实现的方法可以不用再实现了。类似的还有static方法。现在这种接口除了上面提到的,还有BiConsumer,BiFunction,BinaryOperation等,在java.util.function包下的接口,大多数都有,后缀为Supplier的接口没有和别的少数接口。
5 lambda 的性能比较
public class AcceptMethod {public static void printValur(String str) {str = str.intern();CharSequence s = str.subSequence(0, 1);}public static void test1() {List<String> al = new ArrayList<String>();for (int i = 0; i < 10000; i++) {al.add("al" + i);}Long startTime = System.currentTimeMillis();for (String a : al) {AcceptMethod.printValur(a);}System.out.println("old:" + (System.currentTimeMillis() - startTime));startTime = System.currentTimeMillis();al.forEach(x -> {AcceptMethod.printValur(x);});System.out.println("new:" + (System.currentTimeMillis() - startTime));startTime = System.currentTimeMillis();al.forEach(AcceptMethod::printValur);System.out.println("new1:" + (System.currentTimeMillis() - startTime));}public static void test2() {HashMap<String, String> al = new HashMap<>();for (int i = 0; i < 10000; i++) {al.put(i+"", i+"");}Long startTime = System.currentTimeMillis();Set<Map.Entry<String, String>> ss = al.entrySet();for (Map.Entry<String, String> entry : ss) {AcceptMethod.printValur(entry.getKey());}System.out.println("old:" + (System.currentTimeMillis() - startTime));startTime = System.currentTimeMillis();al.forEach((x, y) -> {AcceptMethod.printValur(x);});System.out.println("new:" + (System.currentTimeMillis() - startTime));startTime = System.currentTimeMillis();al.forEach(new BiConsumer<String, String>(){@Overridepublic void accept(String t, String u) {AcceptMethod.printValur(t);}});System.out.println("new1:" + (System.currentTimeMillis() - startTime));}public static void test3() {Set<String> al = new HashSet<String>();for (int i = 0; i < 10000; i++) {al.add("al" + i);}Long startTime = System.currentTimeMillis();for (String a : al) {AcceptMethod.printValur(a);}System.out.println("old:" + (System.currentTimeMillis() - startTime));startTime = System.currentTimeMillis();al.forEach(x -> {AcceptMethod.printValur(x);});System.out.println("new:" + (System.currentTimeMillis() - startTime));startTime = System.currentTimeMillis();al.forEach(AcceptMethod::printValur);System.out.println("new1:" + (System.currentTimeMillis() - startTime));}public static void main(String[] args) {AcceptMethod.test2();
// AcceptMethod.test2();
// AcceptMethod.test3();}
}
执行完第一个test1()
old:3
new:30
new1:2
可以看到下面这种写法最慢了。所以不是所有JDK8的特性都是速度变快的。
al.forEach(x -> {
AcceptMethod.printValur(x);
});
执行完第一个test2()
old:3
new:31
new1:2
执行完第一个test3()
old:3
new:32
new1:2
JDK 8 新特性- 学习中相关推荐
- Java8新特性学习_001_(Lambda表达式,函数式接口,方法引用,Stream类,Optional类)
目录 ■代码 ■代码运行结果 ■代码说明 ・44行:Stream的.foreach方法ー参数类型:函数式接口 ・82行:Interface中,default方法 ・92行 Stream的.max方 ...
- Java8新特性学习笔记
Java8新特性学习笔记 文章目录 Java8新特性学习笔记 一.接口和日期处理 1.接口增强 1.1.JDK8以前 VS JDK8 1)接口定义: 1.2.默认方法(default) 1)默认方法格 ...
- jdk7新特性学习笔记
jdk7新特性学习笔记 从网络down了视频看,记录下学过的东西. 1.二进制字面量 JDK7开始,可以用二进制来表示整数(byte,short,int和long),语法:在二进制数值前面加 0b或者 ...
- 【转载保存】java8新特性学习
编者注:Java 8已经公布有一段时间了,种种迹象表明Java 8是一个有重大改变的发行版. 在Java Code Geeks上已经有大量的关于Java 8 的教程了,像玩转Java 8--lambd ...
- 一篇文带你了解JDK 13新特性,保姆级教程!!!
JDK 13新特性介绍 1.1 JDK 各版本主要特性回顾 JDK Version 1.0 1996-01-23 Oak(橡树) 初代版本,伟大的一个里程碑,但是是纯解释运行,使用外挂JIT,性能比较 ...
- JDK 16 新特性,正式发布!程序员:追不上了...
点击"开发者技术前线",选择"星标????" 让一部分开发者看到未来 地址:https://blog.csdn.net/csdnnews/article/det ...
- JDK 13 新特性一览
点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试资料 作者:木九天 my.oschina.net/mdxlcj/blog ...
- Java8新特性学习记录
前言: Java 8 已经发布很久了,很多报道表明Java 8 是一次重大的版本升级.在Java Code Geeks上已经有很多介绍Java 8新特性的文章, 例如Playing with Java ...
- JDK8新特性-学习笔记
雀语笔记连接: https://www.yuque.com/g/u22538081/ghlpft/zcbyis/collaborator/join?token=pofOuJabmo9rgKvS# 邀请 ...
最新文章
- 2021年大数据ZooKeeper(四):ZooKeeper的shell操作
- 工作中常用到的Linux命令
- 文巾解题 14. 最长公共前缀
- java去掉字符串中前后空格函数_JAVA中去掉字符串空格各种方法详解
- 2020-10-13 四元数用法(不讲原理,只讲计算规则)
- Okhttp实用封装
- php csv linux,PHP处理CSV表格,用fgetcsv和fputcsv在数组和CSV间互转
- 全球活跃开发者不足 1500 万,业余爱好者和学生仅占四分之一
- hive on tez集成完整采坑指南(含tez-ui及安全环境)
- Ubuntu五笔输入法的安装过程
- Redis入门指南(三)
- diamond简介和使用
- idea社区版 html,利用IntelliJ IDEA社区版开发servlet
- Tecplot 自定义色谱颜色
- Redis数据结构之集合对象
- JAVA基于JSP的在线人才招聘求职系统【数据库设计、论文、源码、开题报告】
- 手Q游戏中心上线 完美释放娱乐基因
- GOOGLE 手机定位厘米挑战赛选手提到的技巧、方法总结
- HTTP1.1协议-RFC2616-中文版
- h5 input type 属性为tel苹果系统可以直接获取数字短信验证码
热门文章
- maven项目 Java compiler level does not match the version of the installed Java project facet
- SCVMM2012 SP1 之虚拟机克隆
- Android Service LifeCycle
- 携号转网,用户最关心的还是网络质量
- 程序员应具备的职业素质
- Python3.x 基础练习题100例(91-100)
- 使用 XAML 格式化工具:XAML Styler
- Android IPC机制(二)用Messenger进行进程间通信
- jenkins 拉取git源码超时
- 【Python爬虫】信息组织与提取方法