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 ...
随机推荐
- sas transpose 代码备忘
OPTIONS NOCENTER LS=MAX PS=MAX; LIBNAME S '.\report';/*PROC PRINT DATA=S.doquestionr(WHERE=(sid=1972 ...
- supervisor管理hive metastore和hive server2进程
1. hive_metastore.ini [program:hive_metastore] environment = JAVA_HOME=/usr/java/jdk1..0_172-amd64,H ...
- C#语言正则用法
string phone =""; string pattern @"|\d{10}"; bool rusurt = false; Console.WriteL ...
- 对mysql事务提交、回滚的错误理解
一.起因 begin或者START TRANSACTION开始一个事务 rollback事务回滚 commit 事务确认 人们对事务的解释如下:事务由作为一个单独单元的一个或多个SQL语句组成,如果其 ...
- nvm+nodejs+npm
安装nvm 1.下载nvm包,地址:https://github.com/coreybutler/nvm-windows/releases选择nvm-setup.zip下载, 解压,双击安装即可 2. ...
- VMware虚拟机上配置nginx后,本机无法访问问题
nginx装在CentOS上,用本机访问虚拟机的时候却出现了不能访问的问题,查了资料以后,原来是防火墙的问题.具体情况如下:防火墙可以ping通虚拟机,虚拟机也可以ping通防火墙.接着检查了服务器端 ...
- 关于微信小程序更新内容后手机上不能及时显示的办法
这几天一直在做微信小程序的二次开发,每天都要发布程序,但是发布之后微信上查看小程序和以前的一模一样,丝毫没有改变,但是我再本地上却改变了,而且没有开的不校验合法域名那个.这是为啥呢????? 这是跟小 ...
- 1.spring boot起步之Hello World【从零开始学Spring Boot】
[视频&交流平台] àSpringBoot视频 http://study.163.com/course/introduction.htm?courseId=1004329008&utm ...
- Check Kernel version of J2EE Engine
1912674 - How to check kernel version of an AS Java Two types of the kernel are in SAP NetWeaver Jav ...
- CMD下的netstat命令
查询端口启用情况 netstat -ano|findstr 80