JAVA8-待续
1. 函数式编程,因为在并发和时间驱动编程中的优势,函数式编程又逐渐流行起来
以前是实现一个比较器需要实现Comparator接口,并重写compare方法,以下为两种实现方法(类似还有线程,事件等):
class compOldClass implements Comparator<String> {
@Override
public int compare(String first, String second) {
return Integer.compare(first.length(), second.length());
}
}
Comparator<String> compOld = new Comparator<String>() {
@Override
public int compare(String first, String second) {
return Integer.compare(first.length(), second.length());
}
};
在JDK8中,很多接口添加@FunctionalInterface被声明为函数式接口,JDK8的接口中可以有default和static方法,函数式接口中除了覆盖Object的方法之外,只允许有一个抽象方法
@FunctionalInterface
public interface Comparator<T> {
......
int compare(T o1, T o2);
boolean equals(Object obj);
......
default Comparator<T> reversed() {
return Collections.reverseOrder(this);
}
......
......
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
}
......
}
JDK8函数方式的Comparator实现
Comparator<String> comp = (first, second) -> Integer.compare(first.length(), second.length());
自定义测试:就是迭代元素,提供处理方法,进行处理
@FunctionalInterface
interface WorkerSep {
public void doSthSep(String conent);
}
com.timer.WorkerSep workerSep = (x) -> System.out.println(x);
List<String> lists = new ArrayList<String>();
lists.add("a");
lists.add("b");
lists.stream().forEach(workerSep::doSthSep);
方法引用(对象::实例方法 / 类::静态方法 / 类::实例方法 / 类::new (支持多个构造器根据参数选择最合适的)):例为调用父类方法,传入线程中执行
/**
* Created by itworker365 on 5/19/2017.
*/
public class Java8ThreadTest {
public static void main (String[] args) {
ConcurrentWorker concurrentWorker = new ConcurrentWorker();
concurrentWorker.doSth();
}
}
class Worker {
public void doSth() {
System.out.print("working......");
}
}
class ConcurrentWorker extends Worker {
public void doSth () {
Thread thread = new Thread(super::doSth);
thread.start();
}
}
2. Stream
例,读文件 拆分字符 打印 , 流处理的时候原字符不变,将输入流处理后传到下一个流处理器直到结束,输出的新字符为处理过后的,换成parallelStream就是并行的了,代码流程为创建一个stream,执行一些列操作,使用一个终止符来终止操作,但执行顺序为print被调用的时候,采取找数据,开始计算。
Collection接口中添加stream方法,可以将任何一个集合转换为stream,即使数组也可以Stream.of(数组),Stream.generate(),Stream.iterator(),Pattern.compile(正则).splistAsStream("****"),Files.lines(path)等
String content = new String(Files.readAllBytes(Paths.get("d:\\a.txt")));
List<String> words = Arrays.asList(content.split(","));
//过滤掉fileter中运算为false的
words.stream().filter(w -> w.startsWith("b")).forEach(System.out::println);
//每行都执行以下map里的函数
words.stream().map(String::toUpperCase).map(s -> s.charAt(0)).forEach(System.out::println);
//不停输入,直到Limit,skip表示忽略掉前n个元素
Stream.iterate(1, item -> item + 1).limit(10).forEach(System.out::println);
//将每一行拆分为一个流添加到原来computer,it-worker ==》computer it worker
words.stream().flatMap(article -> Stream.of(article.split("-"))).forEach(System.out::println);
//perk显示元素是否被取用,count统计个数,同时局和方法还有max,min,findFirst,findAny,anyMatch等
words.stream().peek(System.out::println).count();
//有状态的转换,排序和去重等操作,需要记录元素状态,进行操作
words.stream().distinct().forEach(System.out::println);
//判断是否存在符合条件的元素optional元素还可以ifPresent,map,orElse等添加处理
Optional<String> optional = words.stream().filter(w -> w.startsWith("c")).findAny();
if (optional.isPresent()) {
System.out.println("option result: " + optional.get());
}
System.out.println("any match: " + words.stream().anyMatch(w -> w.startsWith("c")));
//将stream转为数组
String[] wordArray = words.stream().toArray(String[]::new);
//其他收集方式,其他方式类似,需要时查看API
Set<String> hashSet = words.stream().collect(Collectors.toSet());
List<String> list = words.stream().collect(Collectors.toList());
TreeSet<String> treeSet = words.stream().collect(Collectors.toCollection(TreeSet<String>::new));
Map<String,String> map = words.stream().collect(Collectors.toMap(x -> x, String::toUpperCase));
String result = words.stream().collect(Collectors.joining("/"));
//分组分片 same as String::toUpperCase
Map<String, List<String>> splitMap = words.stream().collect(Collectors.groupingBy(x -> x.toUpperCase()));
Map<Boolean, List<String>> partitionMap = words.stream().collect(Collectors.partitioningBy(x -> x.toUpperCase().equals("CD")));
//所有字符串concat在一起
String s = words.stream().reduce("", (a, b) -> a.concat(b));
System.out.println("reduce : " + s);
3.日期函数更新
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAdjuster; /**
* Created by itworker365 on 5/19/2017.
*/
public class Jdk8NewTimmer {
public static void main (String[] args) {
Instant start = Instant.now();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println(duration.toMillis());
System.out.println(duration.toMinutes()); LocalDate localDate = LocalDate.now();
System.out.println(localDate.getYear() + " " + localDate.getMonth());
LocalDate localDateMe = LocalDate.of(2008, 8, 8);
System.out.println(localDateMe.getYear() + " " + localDateMe.getMonth());
//2017年第十天
LocalDate someDay = localDate.of(2017,1,1).plusDays(10); //可以用.with方法调整不同的作息周期,还可以用withHout等调整对应的具体时间
TemporalAdjuster NEXT_WORKDAY = w -> {
LocalDate localDate1 = (LocalDate)w;
do {
localDate1 = localDate1.plusDays(1);
} while (localDate1.getDayOfWeek().getValue() >= 6);
return localDate1;
};
LocalDate backToWork = localDate.with(NEXT_WORKDAY);
System.out.println(backToWork.toString());
//时间根据时区调整
ZonedDateTime zonedDateTime = ZonedDateTime.of(2017,5,1,1,1,1,1, ZoneId.of("America/New_York"));
System.out.println(zonedDateTime.toString()); //各种日期信息打印格式模板
String format = DateTimeFormatter.ISO_DATE.format(localDate);
System.out.println(format);
//变为本土化显示,ofPattern自定义格式。
DateTimeFormatter format1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
System.out.println(format1.format(zonedDateTime));
}
}
JAVA8-待续的更多相关文章
- Java8函数式接口以及lambda表达式实践
罗列一下遇到可以转换成lamada表达式的场景,仅供参考,如有更好的方式,欢迎在评论区留言. 1.计算订单总金额 订单总金额一般是在后台循环叠加每个购买商品的金额已获取到,通常的方式如下 BigDec ...
- java8新特性(六):Stream多线程并行数据处理
转:http://blog.csdn.net/sunjin9418/article/details/53143588 将一个顺序执行的流转变成一个并发的流只要调用 parallel()方法 publi ...
- Java8 时间处理类的使用实践(LocalDate...)
有了它,谁还在用Date?Calendar? 其实也不能这么绝对,毕竟还没到那个程度上.Java8 新增了处理时间的一组类(LocalDate.LocalDateTime.LocalTime),刚开始 ...
- Java8实战分享
虽然很多人已经使用了JDK8,看到不少代码,貌似大家对于Java语言or SDK的使用看起来还是停留在7甚至6. Java8在流式 or 链式处理,并发 or 并行方面增强了很多,函数式的风格使代码可 ...
- java8中lambda表达式的应用,以及一些泛型相关
语法部分就不写了,我们直接抛出一个实际问题,看看java8的这些新特性究竟能给我们带来哪些便利 顺带用到一些泛型编程,一切都是为了简化代码 场景: 一个数据类,用于记录职工信息 public clas ...
- javascript有用小功能总结(未完待续)
1)javascript让页面标题滚动效果 代码如下: <title>您好,欢迎访问我的博客</title> <script type="text/javasc ...
- ASP.NET MVC 系列随笔汇总[未完待续……]
ASP.NET MVC 系列随笔汇总[未完待续……] 为了方便大家浏览所以整理一下,有的系列篇幅中不是很全面以后会慢慢的补全的. 学前篇之: ASP.NET MVC学前篇之扩展方法.链式编程 ASP. ...
- Android Studio2.1.2 Java8环境下引用Java Library编译出错
转载请注明出处:http://www.cnblogs.com/LT5505/p/5685242.html 问题:在Android Studio2.1.2+Java8的环境下,引用Java Librar ...
- Java笔记——Java8特性之Lambda、方法引用和Streams
Java8已经推出了好一段时间了,而掌握Java8的新特性也是必要的,如果要进行Spring开发,那么可以发现Spring的官网已经全部使用Java8来编写示例代码了,所以,不学就看不懂. 这里涉及三 ...
- 关于DOM的一些总结(未完待续......)
DOM 实例1:购物车实例(数量,小计和总计的变化) 这里主要是如何获取页面元素的节点: document.getElementById("...") cocument.query ...
随机推荐
- 【ZZ】终于有人把云计算、大数据和人工智能讲明白了!
终于有人把云计算.大数据和人工智能讲明白了! https://mp.weixin.qq.com/s/MqBP0xziJO-lPm23Bjjh9w 很不错的文章把几个概念讲明白了...图片拷不过来... ...
- MySQL学习----各种字符的长度总结
数字型 类型 大小 范围(有符号) 范围(无符号) 用途 TINYINT 1 字节 (-128,127) (0,255) 小整数值 SMALLINT 2 字节 (-32 768,32 767) (0, ...
- [UE4]Lock Always
创建一个Widget加到视图,指定为鼠标焦点,并显示鼠标 Lock Always:叫鼠标锁定在游戏窗口内.
- 高通9X07模块QMI架构使用入门
QMI(Qualcomm Message Interface) 高通用来替代OneRPC/DM的协议,用来与modem通信.本文是摸索高通QMI机制一点经验,重点解读了如果建立拨号连接,仅供参考.qm ...
- 本地IP,掩码,网关,DNS设置
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Web api Json 接受的参数类型为父类,自动序列化为子类的过程
场景: public abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// t ...
- HDFS操作及小文件合并
小文件合并是针对文件上传到HDFS之前 这些文件夹里面都是小文件 参考代码 package com.gong.hadoop2; import java.io.IOException; import j ...
- 洛谷 P2629 好消息,坏消息
题目描述 uim在公司里面当秘书,现在有n条消息要告知老板.每条消息有一个好坏度,这会影响老板的心情.告知完一条消息后,老板的心情等于之前老板的心情加上这条消息的好坏度.最开始老板的心情是0,一旦老板 ...
- es6(9)--Symbol
//Symbol生成一个独一无二的值,生成的值不会相等 { //声明1 let a1=Symbol(); let a2=Symbol(); console.log(a1===a2);//false / ...
- [python] 初学python,级联菜单输出
#Author:shijt china_map = { "河北": { '石家庄': ['辛集', '正定', '晋州'], '邯郸': ['涉县', '魏县', '磁县'], ' ...