├── Java 8函数式编程.pdf
├── Java 8实战.pdf
├── README.md
├── pom.xml
└── src
└── main
└── java
├── Optional
└── OptionalTest.java
├── date
├── DataExcample2.java
└── DateExample.java
├── javaScript
└── JavaScriptDemo.java
├── lambda
├── InterfaceInner.java
├── LambdaExample.java
├── LamdbaTest.java
├── User.java
├── UserArgsInterface.java
└── UserInterface.java
├── methodReference
├── MethodReference.java
└── Student.java
└── stream
└── SteamMethod.java
/Java 8函数式编程.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eratel/JDK8/c8b147f0067c200f3f2521f652854cb0b24d412e/Java 8函数式编程.pdf
--------------------------------------------------------------------------------
/Java 8实战.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eratel/JDK8/c8b147f0067c200f3f2521f652854cb0b24d412e/Java 8实战.pdf
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | * GitHub: https://github.com/ABHSY
2 | * author: ABHSY.Klein
3 |
4 |
5 | **有相对jvm 多线程并发 以及 lamdba 函数式编程的小伙伴。**
6 | * 感兴趣的添加我的**Q425359983**
7 | * 或有问题咨询也加**Q425359983**
8 |
9 |
10 | **对微服务有兴趣的可以看我的springclound的Repositiories**
11 | * 技术范围:包含EUREKA FEIGN ZULL HYSTRIX ZULL SPRINGCONFIG TUBINE HYSTRIXDASHBORD 以及通过sidecar 异构非java语言的微服务
12 | * GitHub:https://github.com/ABHSY/springCloud.git
13 |
14 | **对前端有兴趣的小伙伴可以看我的前端博客**
15 | * 技术范围:vue + vue-cli + element + vue-rouse + vue-router + es6 + webpack
16 | * GitHub:https://github.com/ABHSY/VUE-CLI-ELEMENTUI.git
17 |
18 |
19 | * 刚入门的小伙伴可以看我的springBoot 集成
20 | * mybatis quartz servert sole task springData
21 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | groupId
8 | jdk8
9 | 1.0-SNAPSHOT
10 |
11 |
12 |
13 | org.apache.maven.plugins
14 | maven-compiler-plugin
15 |
16 | 1.8
17 | 1.8
18 |
19 |
20 |
21 |
22 |
23 |
24 | org.projectlombok
25 | lombok
26 | 1.16.16
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | junit
35 | junit
36 | 4.12
37 |
38 |
39 | org.apache.commons
40 | commons-lang3
41 | 3.4
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/src/main/java/Optional/OptionalTest.java:
--------------------------------------------------------------------------------
1 | package Optional;
2 |
3 | import lambda.User;
4 | import org.junit.Test;
5 |
6 | import java.util.Optional;
7 |
8 | /**
9 | * @program: jdk8
10 | * @GitHub: https://github.com/ABHSY
11 | * @author: ABHSY.Jason
12 | * @create: 2018-03-31 16:16
13 | * 接口调用
14 | **/
15 | public class OptionalTest {
16 |
17 | public void test(User u){
18 | Optional optional = Optional.ofNullable(u);
19 | System.out.println(optional.orElse("nullPoint"));
20 | }
21 | @Test
22 | public void test2(){
23 | test(new User());
24 | test(null);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/date/DataExcample2.java:
--------------------------------------------------------------------------------
1 | package date;
2 |
3 | import org.junit.Test;
4 |
5 | import java.time.LocalDate;
6 | import java.time.LocalTime;
7 | import java.time.MonthDay;
8 |
9 |
10 | public class DataExcample2 {
11 | private LocalDate today = LocalDate.now();
12 |
13 | @Test
14 | public void testData(){
15 | LocalDate of = LocalDate.of(2014,4,1);
16 | // System.out.print(of.equals(today));
17 |
18 | LocalDate localDate = today.plusDays(1);
19 | // boolean after = localDate.isAfter(of);
20 | System.out.print(localDate.isBefore(of));
21 |
22 |
23 | LocalDate datebirth = LocalDate.of(1994, 4, 1);
24 | MonthDay of1 = MonthDay.of(datebirth.getMonth(), datebirth.getDayOfMonth());
25 | MonthDay currentMonthDay = MonthDay.from(today);
26 |
27 |
28 | }
29 |
30 | @Test
31 | public void equalsData(){
32 | LocalDate of = LocalDate.of(2014, 4, 1);
33 |
34 | LocalDate localDate = today.plusDays(1);
35 | System.out.print(today.isAfter(of));
36 |
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/date/DateExample.java:
--------------------------------------------------------------------------------
1 | package date;
2 |
3 | import org.junit.Test;
4 |
5 | import java.time.*;
6 | import java.time.format.DateTimeFormatter;
7 | import java.time.temporal.ChronoUnit;
8 | import java.time.temporal.TemporalAdjusters;
9 |
10 | import static java.time.temporal.ChronoUnit.DAYS;
11 |
12 | /**
13 | * jdk8 时间处理
14 | * 用到的方法都是线程安全的
15 | */
16 | public class DateExample {
17 | private LocalDate today = LocalDate.now();
18 |
19 | /**
20 | * 时间相关的获取
21 | */
22 | @Test
23 | public void test() {
24 | //获取当前日期
25 | System.out.println("今天的日期 : " + today);
26 |
27 |
28 | //获取单独的年月日
29 | int year = today.getYear();
30 | int month = today.getMonthValue();
31 | int day = today.getDayOfMonth();
32 | System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);
33 |
34 |
35 | //输出当前时间 不包含日期
36 | LocalDateTime now = LocalDateTime.now();
37 | LocalTime time = LocalTime.now();
38 | System.out.println("LocalDateTime : " + now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd/hh/ss")));
39 |
40 | //输出当前的日期和时间
41 | LocalDateTime localDateTime = LocalDateTime.now();
42 | System.out.println("今天的时间和日期:" + localDateTime);
43 | }
44 |
45 | /**
46 | * 时间相关的比较、检查和验证
47 | */
48 | @Test
49 | public void test2() {
50 |
51 |
52 | //LocalDate重写了equals方法,可以直接比较两个LocalDate
53 | LocalDate date1 = LocalDate.of(2014, 1, 14);
54 | if (!date1.equals(today)) {
55 | System.out.printf("Today %s and date1 %s are same date %n", today, date1);
56 | }
57 |
58 |
59 | //日期大小比较
60 | LocalDate tomorrow = today.plusDays(1);
61 | if (tomorrow.isAfter(today)) {
62 | System.out.println("Tomorrow comes after today");
63 | }
64 | LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
65 | if (yesterday.isBefore(today)) {
66 | System.out.println("Yesterday is day before today");
67 | }
68 |
69 |
70 | //日期检查
71 | LocalDate dateOfBirth = LocalDate.of(2017, 5, 16);
72 | MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
73 | MonthDay currentMonthDay = MonthDay.from(today);
74 | if (currentMonthDay.equals(birthday)) {
75 | System.out.println("Many Many happy returns of the day !!");
76 | } else {
77 | System.out.println("Sorry, today is not your birthday");
78 | }
79 |
80 |
81 | YearMonth yearMonth = YearMonth.now();
82 | DayOfWeek dayOfWeek = DayOfWeek.of(2);
83 | System.out.println("年月:" + yearMonth);
84 | System.out.println("几号:" + MonthDay.now());
85 | System.out.println("星期几:" + dayOfWeek);
86 |
87 | //检查是否是闰年
88 | System.out.println(today.isLeapYear());
89 | System.out.println(today.minus(1, ChronoUnit.YEARS).isLeapYear());
90 |
91 |
92 | LocalDate addMonth = today.plusMonths(-2).plusWeeks(2).plusDays(2);
93 |
94 |
95 | //Period是一个时间容器,做比较比较好用
96 | Period period = Period.between(addMonth, today);
97 | //两个日期相差的天数 月份并不会转换成天数。相应的也有getMonths() getYear()方法
98 | System.out.println(period.getDays());
99 | //这个方法为判断传入的年月日是否是负数,不知道是啥用
100 | period.isNegative();
101 | //在当前年月日的基础之上加上指定的天数,月份或者年份
102 | System.out.println(period.withDays(2).getDays());
103 | //该方法判断Period容器中的年月日是否都是0
104 | period.isZero();
105 | //将Period中的年月日进行翻倍
106 | period = period.multipliedBy(3);
107 | System.out.println(period.getDays());
108 | //将时间差进行反转,比如year:2 month:-1 day:15 转换成 year:-2 month: 1 day: -15
109 | period.negated();
110 | //将年转换成月之后,统计总月数
111 | period.toTotalMonths();
112 | //将总月份或者年加上超过12个月的月份,根据一年12个月进行格式化。
113 | period.normalized();
114 |
115 | }
116 |
117 | /**
118 | * 时间格式转换
119 | */
120 | @Test
121 | public void test3() {
122 |
123 |
124 | //时间转换
125 | String dayAfterTommorrow = "20170516";
126 | //2014-01-16
127 | LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
128 | DateTimeFormatter.BASIC_ISO_DATE);
129 | //DateTimeFormatter 内置了很多时间格式化器 同上
130 | System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
131 |
132 | //这种格式的可以直接parse
133 | LocalDate endOfFeb = LocalDate.parse("2017-05-16");
134 | System.out.println(endOfFeb);
135 |
136 | //自定义格式
137 | String goodFriday = "05 18 2017";
138 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy");
139 | LocalDate holiday = LocalDate.parse(goodFriday, formatter);
140 | System.out.printf("Successfully parsed String %s, date is %s%n", goodFriday, holiday);
141 | }
142 |
143 | /**
144 | * 时间相关的操作 和一些常用的时间提取
145 | */
146 | @Test
147 | public void test1() {
148 |
149 |
150 | //自定义日期
151 | LocalDate dateOfBirths = LocalDate.of(2010, 1, 14);
152 | System.out.println("Your Date of birth is : " + dateOfBirths);
153 |
154 |
155 | //时间变化
156 | LocalDate addToday = today.plusDays(2);
157 | LocalDate addMonth = today.minusDays(1);
158 | //Duration这个类没用懂 类似的方法在165行
159 | // System.out.println("测试minus :" + today.minus(Duration.ofDays(1589713165)));
160 |
161 |
162 | //增加两个世纪
163 | LocalDate newEras = today.plus(2, ChronoUnit.CENTURIES);
164 | System.out.println(addToday);
165 | System.out.println(newEras);
166 |
167 |
168 | //minus和plus是相反的 也是修改日期相关的
169 | LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
170 | System.out.println("Date before 1 year : " + previousYear);
171 | LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
172 | System.out.println("Date after 1 year : " + nextYear);
173 |
174 |
175 | //时间戳
176 | Instant timestamp = Instant.now();
177 | System.out.println("time:" + timestamp.getEpochSecond());
178 |
179 | Instant instant = Instant.ofEpochSecond(timestamp.getEpochSecond());
180 | System.out.println(LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai")));
181 |
182 |
183 | //TemporalAdjusters封装很多提取时间的方法
184 | // 取本月第1天:
185 | LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth()); // 2014-12-01
186 | // 取本月第2天:
187 | LocalDate secondDayOfThisMonth = today.withDayOfMonth(2); // 2014-12-02
188 | // 取本月最后一天,再也不用计算是28,29,30还是31:
189 | LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 2014-12-31
190 | // 取下一天:
191 | LocalDate firstDayOf2015 = lastDayOfThisMonth.plusDays(1); // 变成了2015-01-01
192 | // 取2015年1月第一个周一,这个计算用Calendar要死掉很多脑细胞:
193 | LocalDate firstMondayOf2015 = LocalDate.parse("2015-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); // 2015-01-05
194 |
195 | //以下方法基本上都是LocalDate LocalDateTime LocalTime三个类通用的,小有区别
196 | //今年的第355天的日期
197 | System.out.println("测试withDayOfYear :" + today.withDayOfYear(355));
198 | //当前日期的在一月的日期,如果当前日期的在响应的月份没有则取当月的最后一天。比如取3月31,如果月份换成2月,2月没有31天它会直接判断今年是平年还是闰年然后取最后一天。
199 | System.out.println("测试withDayOfMonth :" + today.withMonth(1));
200 | System.out.println("测试:" + LocalDate.now().plusDays(14).withMonth(2));
201 | //本月第二天的日期
202 | System.out.println("测试withDayOfWeek:" + today.withDayOfMonth(2));
203 | //显示哪一年的今天的日期
204 | System.out.println("测试withYear" + today.withYear(1995));
205 |
206 |
207 | //TemporalAdjusters有封装的选取指定日期的方法。如今年的第一天,明年的第一天,下个月的最后一天,本月的最后一天等等方法都有封装
208 | //返回今天零点的LocalDateTime
209 | System.out.println("返回今天零点的LocalDateTime:" + today.atStartOfDay());
210 | //返回一个今天的指定时区的ZoneDateTime
211 | System.out.println("返回一个今天的达尔文的ZoneDateTime : " + today.atStartOfDay(ZoneId.of("Australia/Darwin")));
212 | //返回今天两点二十的时间
213 | System.out.println(today.atTime(2, 20));
214 | System.out.println(today.atTime(LocalTime.of(2, 20, 20, 321)));
215 | }
216 |
217 | @Test
218 | public void test5() {
219 | //时钟
220 | /*
221 | map.put("ACT", "Australia/Darwin");
222 | map.put("AET", "Australia/Sydney");
223 | map.put("AGT", "America/Argentina/Buenos_Aires");
224 | map.put("ART", "Africa/Cairo");
225 | map.put("AST", "America/Anchorage");
226 | map.put("BET", "America/Sao_Paulo");
227 | map.put("BST", "Asia/Dhaka");
228 | map.put("CAT", "Africa/Harare");
229 | map.put("CNT", "America/St_Johns");
230 | map.put("CST", "America/Chicago");
231 | map.put("CTT", "Asia/Shanghai");
232 | map.put("EAT", "Africa/Addis_Ababa");
233 | map.put("ECT", "Europe/Paris");
234 | map.put("IET", "America/Indiana/Indianapolis");
235 | map.put("IST", "Asia/Kolkata");
236 | map.put("JST", "Asia/Tokyo");
237 | map.put("MIT", "Pacific/Apia");
238 | map.put("NET", "Asia/Yerevan");
239 | map.put("NST", "Pacific/Auckland");
240 | map.put("PLT", "Asia/Karachi");
241 | map.put("PNT", "America/Phoenix");
242 | map.put("PRT", "America/Puerto_Rico");
243 | map.put("PST", "America/Los_Angeles");
244 | map.put("SST", "Pacific/Guadalcanal");
245 | map.put("VST", "Asia/Ho_Chi_Minh");
246 | map.put("EST", "-05:00");
247 | map.put("MST", "-07:00");
248 | map.put("HST", "-10:00");
249 | */
250 | LocalDateTime datetime = LocalDateTime.of(2017, Month.JANUARY, 14, 19, 30);
251 | ZoneOffset offset = ZoneOffset.of("+05:30");
252 | OffsetDateTime date = OffsetDateTime.of(datetime, offset);
253 | System.out.println("Date and Time with timezone offset in Java : " + date);
254 |
255 |
256 | //拿取偏移量
257 | ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("America/New_York"));
258 | ZonedDateTime china = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Asia/Shanghai"));
259 | ZonedDateTime Darwin = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Australia/Darwin"));
260 | System.out.println("America : " + zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
261 | System.out.println("China : " + china);
262 |
263 |
264 | //拿取具体时区的时间
265 | System.out.println("偏移时间" + LocalDateTime.now(Clock.fixed(Instant.now(), ZoneId.of("Australia/Darwin"))));
266 | System.out.println("Darwin : " + Darwin.getOffset());
267 | System.out.println("Now : " + LocalDateTime.now());
268 | }
269 | /*
270 | 总结:
271 | LocalDate、LocalDate、LocalDateTime、YearMonth、MonthDay、DayOfWeek都支持 :
272 | plus加时间,
273 | minus减时间,
274 | */
275 | }
276 |
--------------------------------------------------------------------------------
/src/main/java/javaScript/JavaScriptDemo.java:
--------------------------------------------------------------------------------
1 | package javaScript;
2 | import org.junit.Test;
3 |
4 | import javax.script.ScriptEngine;
5 | import javax.script.ScriptEngineManager;
6 | import javax.script.ScriptException;
7 |
8 | public class JavaScriptDemo {
9 | @Test
10 | public void test() throws ScriptException {
11 | ScriptEngineManager manager = new ScriptEngineManager();
12 | ScriptEngine engine = manager.getEngineByName( "JavaScript" );
13 | System.out.println(engine.getClass().getName());
14 | String s = "function f() { return 1; }; f() + 1;";
15 | System.out.println(engine.eval(s));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/lambda/InterfaceInner.java:
--------------------------------------------------------------------------------
1 | package lambda;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * @program: jdk8
10 | * @GitHub: https://github.com/ABHSY
11 | * @author: ABHSY.Jason
12 | * @create: 2018-03-31 16:16
13 | * 接口调用
14 | **/
15 | public class InterfaceInner {
16 | ////////////////////////////////////////////////////////////////
17 | // 接口调用
18 | /** lambda第一种格式,无参 */
19 | /**
20 | * 无非就是将实现 作为参数 使用lamdba表达式的形式实现
21 | * 然后在类中被调用
22 | */
23 | @Test
24 | public void test(){
25 | eat(() -> System.out.println("-----------"));
26 | }
27 |
28 | /**
29 | * 当你在实现底层框架 实现lamdba的形式时。 这块写入base 业务逻辑
30 | * 传输 关键业务逻辑
31 | */
32 | private void eat(UserInterface c){
33 | c.eat();
34 | }
35 |
36 |
37 | /**
38 | * lambda第二种格式 ,有参
39 | */
40 | @Test
41 | public void test1(){
42 | study( user -> System.out.println(user.getName()));
43 | }
44 |
45 | private void study(UserArgsInterface c){
46 | c.study(new User("name",10)); //传入直接代码片段 对接口实现可以这么理解
47 | c.welcome(); //直接执行接口中的方法
48 | }
49 |
50 |
51 |
52 |
53 |
54 | ////////////////////////////////////////////////////////////////////////////////////////
55 |
56 | /**
57 | * for 循环
58 | */
59 | @Test
60 | public void getLoopList() {
61 | List all = new ArrayList<>();
62 | for (int i = 0; i < 10; i++) {
63 | all.add(new User("111"+i, 11));
64 | }
65 | all.forEach(user -> System.out.print(user));
66 |
67 | }
68 |
69 | public void lambdaLoopList(List list) {
70 | //三行循环效果相同
71 | //list.forEach(user -> System.out.println(user.toString()));
72 | //list.forEach(user -> System.out.println(user));//下面一行代码就是简写形式
73 | list.forEach(System.out::println);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/lambda/LambdaExample.java:
--------------------------------------------------------------------------------
1 | package lambda;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * @program: jdk8
9 | * @GitHub: https://github.com/ABHSY
10 | * @author: ABHSY.Jason
11 | * @create: 2018-03-31 16:16
12 | * 匿名内部类 比较 等
13 | **/
14 | public class LambdaExample {
15 | @Test
16 | public void test() {
17 | List wordList = Arrays.asList("123456", "1234", "123", "12", "11111");
18 |
19 |
20 | System.out.println(compare(wordList));
21 | System.out.println(compareLambda(wordList));
22 | System.out.println(compareLambdaFunction(wordList));
23 |
24 |
25 | }
26 |
27 | //匿名内部类
28 | public List compare(List wordList) {
29 |
30 | wordList.sort(new Comparator() {
31 | @Override
32 | public int compare(String s1, String s2) {
33 | return Integer.compare(s1.length(), s2.length());
34 | }
35 | });
36 | return wordList;
37 | }
38 |
39 | //lambda
40 | //Integer.compare 输出结果 大于=1;等于=0;小于=-1
41 | public List compareLambda(List wordList) {
42 | wordList.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));
43 | return wordList;
44 | }
45 |
46 | //函数(非空验证)
47 | public List compareLambdaFunction(List wordList) {
48 | wordList.sort(Comparator.comparingLong(String::length));
49 | // wordList.sort(Comparator.comparingLong((a) -> a.length()));
50 | return wordList;
51 | }
52 |
53 |
54 | public void treeSetCompare() {
55 |
56 | Set set = new TreeSet<>(Comparator.comparing(User::getAge));
57 | //原来的写法
58 | Set oldSet = new TreeSet<>(new Comparator() {
59 | @Override
60 | public int compare(User o1, User o2) {
61 | return o1.getAge() - o2.getAge();
62 | }
63 | });
64 | }
65 |
66 |
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/src/main/java/lambda/LamdbaTest.java:
--------------------------------------------------------------------------------
1 | package lambda;
2 |
3 | import org.junit.Test;
4 |
5 | import java.text.SimpleDateFormat;
6 | import java.util.*;
7 | import java.util.concurrent.atomic.AtomicInteger;
8 | import java.util.function.Function;
9 | import java.util.stream.Collectors;
10 | import java.util.stream.Stream;
11 |
12 | import static java.util.Arrays.asList;
13 | import static java.util.stream.Collectors.*;
14 | import static junit.framework.Assert.assertEquals;
15 |
16 | /**
17 | * @program: jdk8
18 | * @GitHub: https://github.com/ABHSY
19 | * @author: ABHSY.Jason
20 | * @create: 2018-03-31 16:16
21 | **/
22 | public class LamdbaTest {
23 |
24 | public static void main(String arg[]) {
25 | List strings = Arrays.asList("name", "name1", "name2");
26 | long l = fromLondonPrinted(strings);
27 | System.out.print(l);
28 | }
29 |
30 | /**
31 | * filter 过滤数据
32 | */
33 | public static long fromLondonPrinted(List allArtists) {
34 | // BEGIN internal_count_londoners_printed
35 | long count = allArtists.stream()
36 | .filter(artist -> {
37 | System.out.println(artist);
38 | return artist.equals("name");
39 | })
40 | .count();
41 | // END internal_count_londoners_printed
42 | return count;
43 | }
44 |
45 | @Test
46 | /**
47 | * map 操作符
48 | */
49 | public void allToUpperCase() {
50 | // Stream a = Stream.of("a", "b", "c");
51 | // List collect = a.map(string -> string.toUpperCase())
52 | // .collect(Collectors.toList());
53 | // System.out.print(collect.toString());
54 |
55 | List strings = Arrays.asList("a", "b", "c");
56 | List list = strings.stream().map(a -> {
57 | return a.toUpperCase();
58 | }).collect(toList());
59 | //将stream转换为List 的对象
60 | // List collect = stringStream.collect(toList());
61 |
62 | }
63 |
64 | /**
65 | * 获取最小 最大
66 | */
67 | @Test
68 | public void streamsMaxLength() {
69 | List uu = asList(new User("Bakai", 524),
70 | new User("Violets for Your Furs", 378),
71 | new User("Time Was", 451));
72 |
73 | User user = uu.stream()
74 | // .min(Comparator.comparing(u -> u.getAge()))
75 | .max(Comparator.comparing(u -> u.getAge()))
76 | .get();
77 | System.out.print(user);
78 | }
79 |
80 | /**
81 | * reduce 求和
82 | */
83 | @Test
84 | public void sumUsingReduce() {
85 | Optional reduce = Stream.of(1, 2, 3)
86 | .reduce((acc, element) -> acc + element);
87 | System.out.print(reduce.get());
88 | }
89 |
90 | /////////////////////////////////////////////////////////////////////////////////////////////
91 | //以下是练习
92 |
93 | /**
94 | * 找到对象中 name 开头ba 的年龄是多少
95 | */
96 | @Test
97 | public void originsOfBands() {
98 | List userList = asList(new User("Bakai", 524),
99 | new User("Violets for Your Furs", 378),
100 | new User("Time Was", 451));
101 | // BEGIN origins_of_bands
102 | List origins = userList.stream()
103 | //先过滤
104 | .filter(artist -> artist.getName().startsWith("Ba"))
105 | //对年龄进行重新赋值
106 | .map(artist -> artist.getAge())
107 | //将 值装换
108 | .collect(toList());
109 | // END origins_of_bands
110 | System.out.print(origins.toString());
111 | }
112 |
113 | @Test
114 | public void findName() {
115 | List users = asList(new User("Bakai", 524),
116 | new User("Violets for Your Furs", 378),
117 | new User("Time Was", 451));
118 | Set tn = new HashSet<>();
119 | users.stream()
120 | .filter(user -> user.getName().startsWith("B"))
121 | .map(user -> user.getName())
122 | .forEachOrdered(name -> tn.add(name));
123 | // .forEach(name ->tn.add(name));
124 | System.out.print(tn);
125 | }
126 |
127 | //计算流中所有数之和
128 | @Test
129 | public void addUP() {
130 | List wordList = Arrays.asList(1, 2, 3);
131 | Optional reduce = wordList.stream().reduce((nu1, nu2) -> nu1 + nu2);
132 | System.out.print(reduce.get());
133 | }
134 |
135 |
136 | /**
137 | * IntSummaryStatistics int
138 | * LongSummaryStatistics long
139 | * 等等 都包含 man min average sum 这些方法
140 | */
141 | @Test
142 | public void printTrackLengthStatistics() {
143 | List users = asList(new User("Bakai", 524),
144 | new User("Violets for Your Furs", 378),
145 | new User("Time Was", 451));
146 |
147 | IntSummaryStatistics trackLengthStats
148 | = users.stream()
149 | //转换为int类型 自动解包
150 | .mapToInt(user -> user.getAge())
151 | .summaryStatistics();
152 |
153 | System.out.printf("Max: %d, Min: %d, Ave: %f, Sum: %d",
154 | trackLengthStats.getMax(),
155 | trackLengthStats.getMin(),
156 | trackLengthStats.getAverage(),
157 | trackLengthStats.getSum());
158 | }
159 |
160 |
161 | /**
162 | * map 循环
163 | */
164 | @Test
165 | public void countAlbums() {
166 | HashMap map = new HashMap();
167 | map.put("a", 1);
168 | map.put("b", 2);
169 | map.put("c", 3);
170 | Map countOfAlbums = new HashMap<>();
171 | map.forEach((k, v) -> {
172 | countOfAlbums.put(k.toString().toUpperCase(), Integer.parseInt(v.toString()));
173 | });
174 | System.out.print(countOfAlbums.toString());
175 | }
176 |
177 | /**
178 | * ThreadLocal 的 withInitial 传入一个 supplier对象实例来创建对象
179 | */
180 | @Test
181 | public void testThreadLocal() {
182 | //通过工厂方式 JVM少加载一个类
183 | ThreadLocal localFormatter =
184 | ThreadLocal.withInitial(() -> new SimpleDateFormat());
185 | SimpleDateFormat simpleDateFormat = localFormatter.get();
186 | //System.out.print(simpleDateFormat);
187 |
188 | /**
189 | * AtomicInteger 是一个应对多线程 高并发 实现序列化的integer类型
190 | */
191 | AtomicInteger threadId = new AtomicInteger(1);
192 | ThreadLocal localId
193 | = ThreadLocal.withInitial(() -> threadId.incrementAndGet());
194 | int idForThisThread = localId.get();
195 | System.out.print(idForThisThread);
196 | }
197 |
198 |
199 | /**
200 | * HashSet 排序
201 | */
202 | @Test
203 | public void hashSetToStreamSorted() {
204 | // BEGIN HASHSET_TO_STREAM_SORTED
205 | Set numbers = new HashSet<>(asList(4, 3, 2, 1));
206 |
207 | List sameOrder = numbers.stream()
208 | .sorted()
209 | .collect(toList());
210 |
211 | assertEquals(asList(1, 2, 3, 4), sameOrder);
212 | // END HASHSET_TO_STREAM_SORTED
213 | }
214 |
215 |
216 | /**
217 | * 分类 partitioningBy返回布尔类型值进行分类
218 | */
219 | @Test
220 | public void bandsAndSolo1() {
221 | List users = asList(new User("Bakai", 524),
222 | new User("Violets for Your Furs", 378),
223 | new User("Time Was", 451));
224 | Map> collect = users.stream().collect(partitioningBy(user -> user.getAge() == 524));
225 | System.out.print(collect);
226 | }
227 |
228 | /**
229 | * 分类 groupingBy 数据分类
230 | */
231 | @Test
232 | public void bandsAndSolo2() {
233 | List users = asList(new User("Bakai", 524),
234 | new User("Violets for Your Furs", 378),
235 | new User("Violets for Your Furs", 378),
236 | new User("Time Was", 451));
237 | //计数
238 | // Map collect = users.stream().collect(groupingBy(user -> user.getName(), counting()));
239 | //分组
240 | //{451=[User(name=Time Was, age=451)], 378=[User(name=Violets for Your Furs, age=378), User(name=Violets for Your Furs, age=378)], 524=[User(name=Bakai, age=524)]}
241 | Map> collect1 = users.stream()
242 | .collect(groupingBy(User::getAge));
243 | //{451=[451], 378=[378, 378], 524=[524]} //mapping 将两组中搞到一起
244 | Map> collect2 = users.stream()
245 | .collect(groupingBy(User::getAge, mapping(User::getAge, toList())));
246 |
247 | System.out.print(collect2);
248 | }
249 |
250 |
251 | /**
252 | * 首先先通过 map 转换到另外一个容器 通过joining 拼接
253 | * joining 拼接
254 | */
255 | @Test
256 | public void formatArtists() {
257 | List users = asList(new User("Bakai", 524),
258 | new User("Violets for Your Furs", 378),
259 | new User("Violets for Your Furs", 378),
260 | new User("Time Was", 451));
261 | String result =
262 | users.stream()
263 | .map(User :: getName)
264 | //拼接
265 | .collect(joining(", ", "[", "]"));
266 | System.out.print(result);
267 | }
268 |
269 | }
270 |
--------------------------------------------------------------------------------
/src/main/java/lambda/User.java:
--------------------------------------------------------------------------------
1 | package lambda;
2 |
3 | import lombok.Data;
4 |
5 |
6 | @Data
7 | public class User {
8 |
9 | private String name;
10 | private int age;
11 |
12 | public User(String name, int age) {
13 | this.name = name;
14 | this.age = age;
15 | }
16 |
17 | public User() {
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/lambda/UserArgsInterface.java:
--------------------------------------------------------------------------------
1 | package lambda;
2 |
3 | import java.util.function.BinaryOperator;
4 |
5 | //标记在接口上,函数式接口 是指仅仅只包含一个抽象方法的接口
6 | @FunctionalInterface
7 | public interface UserArgsInterface {
8 | void study(User user);
9 | default void welcome(){
10 | System.out.print("welcome+++++++++++++++++++");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/lambda/UserInterface.java:
--------------------------------------------------------------------------------
1 | package lambda;
2 |
3 | @FunctionalInterface
4 | public interface UserInterface {
5 | void eat();
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/methodReference/MethodReference.java:
--------------------------------------------------------------------------------
1 | package methodReference;
2 |
3 | import org.junit.Test;
4 |
5 | import java.awt.event.ActionListener;
6 | import java.util.Arrays;
7 | import java.util.Comparator;
8 | import java.util.List;
9 | import java.util.function.BinaryOperator;
10 | import java.util.function.Consumer;
11 | import java.util.function.Supplier;
12 |
13 | /**
14 | * @program: jdk8
15 | * @GitHub: https://github.com/ABHSY
16 | * @author: ABHSY.Jason
17 | * @create: 2018-03-31 16:16
18 | * 接口调用
19 | **/
20 | public class MethodReference {
21 |
22 | @Test
23 | public void test() {
24 | print2();
25 | System.out.println();
26 | print3();
27 | }
28 |
29 | public static void print2() {
30 | List wordList = Arrays.asList("spring", "summer", "autumn", "winter");
31 | wordList.forEach(word -> System.out.print(word));
32 | }
33 |
34 | public static void print3() {
35 | List wordList = Arrays.asList("spring", "summer", "autumn", "winter");
36 | wordList.forEach(System.out::print);
37 | }
38 |
39 | /**
40 | * 静态方法引用
41 | */
42 | public List sortList1() {
43 | List wordList = Arrays.asList(21, 53, 22);
44 | wordList.sort((w1, w2) -> Integer.compare(w1, w2));
45 | return wordList;
46 | }
47 |
48 | public List sortList2() {
49 | List wordList = Arrays.asList(21, 53, 22);
50 | wordList.sort(Integer::compare);
51 | return wordList;
52 | }
53 |
54 | public List sortList3() {
55 | List wordList = Arrays.asList(21, 53, 22);
56 | wordList.sort(Comparator.comparingInt(a -> a));
57 | return wordList;
58 | }
59 |
60 | @Test
61 | public void test2() {
62 | System.out.println(sortList1().toString());
63 | System.out.println(sortList2().toString());
64 | System.out.println(sortList3().toString());
65 | BinaryOperator tComparator = (x, y) -> x + y;
66 | Runnable runnable = () -> System.out.print(1);
67 | ActionListener tConsumer = event -> System.out.print(1);
68 | Comparator tComparator1 = (x, y) -> x + y;
69 | String name = getName();
70 | Runnable runnable1 = () -> System.out.print(name);
71 | runnable1.run();
72 | }
73 |
74 |
75 |
76 |
77 | public void test3(){
78 | String name = getName();
79 | Runnable runnable = () -> System.out.print(name);
80 | ActionListener actionListener = event -> System.out.print(1);
81 | Runnable runnable1 = () -> {
82 | System.out.print(1);
83 | };
84 | BinaryOperator binaryOperator = (x, y) -> x + y;
85 | BinaryOperator binaryOperator1 = (Long x,Long y) -> x + y;
86 |
87 |
88 |
89 | }
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | public String getName(){
101 | return "111";
102 | }
103 |
104 | @Test
105 | public void test77(){
106 | ActionListener actionListener = e -> {System.out.print(1);};
107 | }
108 |
109 |
110 | /**
111 | * 引用对象方法
112 | */
113 | public String[] sort1() {
114 | String[] words = new String[]{"spring", "summer", "autumn", "winter"};
115 | Arrays.sort(words, (x, y) -> x.compareToIgnoreCase(y));
116 | return words;
117 | }
118 |
119 | public String[] sort2() {
120 | String[] words = new String[]{"spring", "summer", "autumn", "winter"};
121 | Arrays.sort(words, String::compareToIgnoreCase);
122 | return words;
123 | }
124 |
125 | @Test
126 | public void test1() {
127 | System.out.println(Arrays.toString(sort1()));
128 | System.out.println(Arrays.toString(sort2()));
129 | }
130 |
131 | /**
132 | * 构造器引用
133 | */
134 | @Test
135 | public void construct(){
136 | StudentFactory studentFactory = new StudentFactory(Student::new);
137 | }
138 |
139 | static class StudentFactory{
140 | private Supplier supplier;
141 |
142 | StudentFactory(Supplier supplier) {
143 | this.supplier = supplier;
144 | }
145 | }
146 |
147 |
148 | }
149 |
--------------------------------------------------------------------------------
/src/main/java/methodReference/Student.java:
--------------------------------------------------------------------------------
1 | package methodReference;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | /**
8 | * @program: jdk8
9 | * @GitHub: https://github.com/ABHSY
10 | * @author: ABHSY.Jason
11 | * @create: 2018-03-31 16:16
12 | * 接口调用
13 | **/
14 | @Data
15 | @AllArgsConstructor
16 | @NoArgsConstructor
17 | public class Student {
18 | private String name;
19 | private int mathGrade;
20 | private int englishGrade;
21 |
22 |
23 |
24 | public int getGradeCount(){
25 | return mathGrade + englishGrade;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/stream/SteamMethod.java:
--------------------------------------------------------------------------------
1 | package stream;
2 |
3 | import methodReference.Student;
4 | import org.junit.Test;
5 |
6 | import java.util.*;
7 | import java.util.stream.Collectors;
8 | import java.util.stream.Stream;
9 |
10 | /**
11 | * @program: jdk8
12 | * @GitHub: https://github.com/ABHSY
13 | * @author: ABHSY.Jason
14 | * @create: 2018-03-31 16:16
15 | * 接口调用
16 | **/
17 | public class SteamMethod {
18 | private List list = Arrays.asList("111", "112", "131", "4", "5", "6");
19 | private List data = new ArrayList<>();
20 |
21 | {
22 | data.add(new Student("xiaoming", 85, 95));
23 | data.add(new Student("xiaohong", 86, 99));
24 | data.add(new Student("xiaogang", 100, 100));
25 | }
26 |
27 | @Test
28 | public void getDistinct() {
29 |
30 | //去重 distinct(非懒加载)
31 | System.out.println(list.stream().distinct().count());
32 |
33 |
34 | /** 流转换
35 | * 流转换是懒操作的,返回值大多都是Stream,所以才支持链式编程。要想获取转换的数据需要就行聚合操作。通常遇到聚合函数才会开始执行。
36 | **/
37 |
38 | // map 对于Stream中包含的元素使用给定的转换函数进行转换操作,新生成的Stream只包含转换生成的元素。
39 |
40 | //flatmap 对流进行合并
41 | Stream.of(list, list).flatMap(Collection::stream).forEach(System.out::println);
42 |
43 |
44 | System.out.println("----------------------map 对于Stream中包含的元素使用给定的转换函数进行转换操作");
45 | System.out.println(list.stream().map(String::toUpperCase).collect(Collectors.toList()).toString());
46 |
47 | // collect 收集转换后的元素将其转换成map list,同时可以进行分组,排序等一系列操作
48 | System.out.println("----------------------collect 收集转换后的元素将其转换成map list,同时可以进行分组,排序等一系列操作");
49 | System.out.println(list.stream().map(String::toUpperCase).collect(Collectors.toList()).toString());
50 | //set 的唯一特性 会让重复元素去掉
51 | System.out.println(list.stream().map(String::toUpperCase).collect(Collectors.toSet()));
52 | // equipmentSetEffectMetaMap = equipmentSetMetaList.stream().collect(Collectors.toMap(EquipmentSetMeta::getId, EquipmentSetEffectMeta -> EquipmentSetEffectMeta));
53 |
54 |
55 |
56 | //peek 对每一个元素附加处理
57 | System.out.println("---------------------peek 对每一个元素附加处理");
58 | System.out.println(Stream.of("one", "two", "three", "four")
59 | .filter(e -> e.length() > 3)
60 | .peek(e -> System.out.println("Filtered value: " + e))
61 | .map(String::toUpperCase)
62 | .peek(e -> System.out.println("Mapped value: " + e))
63 | .collect(Collectors.toList()));
64 | }
65 |
66 |
67 | @Test
68 | //compareToIgnoreCase 字典排序方式
69 | public void sortedTest(){
70 |
71 | List collect = list.stream().sorted((x, y) -> x.compareToIgnoreCase(y)).collect(Collectors.toList());
72 | System.out.print(collect);
73 | System.out.print(list.stream().sorted((x,y)-> new Integer(x).compareTo(new Integer(y))).collect(Collectors.toList()));
74 |
75 | }
76 |
77 | /**
78 | * 聚合操作(非懒加载)
79 | **/
80 | @Test
81 | public void test3() {
82 |
83 | //max min count 在已有的Stream中获取最大值(需要传入比较器),最小值(需要传入比较器)或者统计总数。
84 | System.out.println("----------------------max min count 在已有的Stream中获取最大值(需要传入比较器),最小值(需要传入比较器)或者统计总数。");
85 | System.out.println(list.stream().filter(w -> w.length() < 4).count());
86 | System.out.println(list.stream().max(Comparator.comparingInt(String::length)));
87 | System.out.println(data.stream().min(Comparator.comparingInt(Student::getGradeCount)));
88 |
89 |
90 | //reduce 在一组数据中生成一个值 max min和count因为常用所以单独提取出来了,原本也是属于reduce操作
91 | System.out.println("----------------------reduce 在一组数据中生成一个值 max min和count因为常用所以单独提取出来了,原本也是属于reduce操作");
92 | //下面是一个累加
93 | int accResult = Stream.of(1, 2, 3, 4)
94 | .reduce(0, (acc, item) -> {
95 | System.out.println("acc : " + acc);
96 | acc += item;
97 | System.out.println("item: " + item);
98 | System.out.println("acc+ : " + acc);
99 | System.out.println("--------");
100 | return acc;
101 | });
102 | System.out.println("accResult: " + accResult);
103 | System.out.println("--------");
104 | //http://blog.csdn.net/io_field/article/details/54971679
105 |
106 | //collect 把Stream中的元素收集到一个容器中去。
107 | System.out.println("----------------------collect 把Stream中的元素收集到一个容器中去。");
108 | List numList = Arrays.asList(1, 1, null, 2, 3, 4, null, 5, 6, 7, 11, 8, 9, 10);
109 | System.out.println(numList.stream().filter(Objects::nonNull).distinct().sorted().collect(Collectors.toList()));
110 |
111 | //pipeline 对集合的并行操作. fork/join 框架,fork 递归式地分解问题,然后每段并行执行,最终由 join 合并结果,返回最后的值。
112 | list.parallelStream();
113 | /*
114 | 1. 是否需要并行?
115 | 2. 任务之间是否是独立的?是否会引起任何竞态条件?
116 | 3. 结果是否取决于任务的调用顺序?
117 | */
118 | /*性能好
119 | ArrayList 、数组或 IntStream.range ,这些数据结构支持随机读取,也就是说它们能轻
120 | 而易举地被任意分解。
121 | 性能一般
122 | HashSet 、 TreeSet ,这些数据结构不易公平地被分解,但是大多数时候分解是可能的。
123 | 性能差 ?
124 | 有些数据结构难于分解,比如,可能要花 O(N) 的时间复杂度来分解问题。其中包括
125 | LinkedList ,对半分解太难了。还有 Streams.iterate 和 BufferedReader.lines ,它们
126 | 长度未知,因此很难预测该在哪里分解。
127 | */
128 |
129 | //forEach 和 forEachOrdered 的区别:Stream中并行处理集合forEach可能会将原本有序的数据进行打乱,forEachOrdered不会出现,仍然保持有序;
130 | System.out.println("----------------------forEach 和 forEachOrdered 的区别:Stream中并行处理集合forEach可能会将原本有序的数据进行打乱,forEachOrdered不会出现,仍然保持有序;");
131 | List aa = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
132 | aa.stream().parallel().forEach(System.out::print);
133 | System.out.println();
134 | aa.stream().parallel().forEachOrdered(System.out::print);
135 | }
136 | /** 短路操作*/
137 | @Test
138 | public void test2(){
139 | //allMatch 判断Stream中的元素是否全部符合要求
140 | boolean allMatch = Stream.of(1, 2, 3, 4)
141 | .allMatch(integer -> integer > 0);
142 | System.out.println("allMatch: " + allMatch); // 打印结果:allMatch: true
143 |
144 | //anyMatch 判断流中是否有一个符合要求的,有一个则返回true
145 | boolean anyMatch = Stream.of(1, 2, 3, 4)
146 | .anyMatch(integer -> integer > 3);
147 | System.out.println("anyMatch: " + anyMatch); // 打印结果:anyMatch: true
148 |
149 | //noMatch 判断流中是否所有的元素都不符合要求,是的话返回true。
150 | boolean noMatch = Stream.of(1, 2, 3, 4)
151 | .noneMatch(integer -> integer < 0);
152 | System.out.println("noMatch: " + noMatch); // 打印结果:noMatch: true
153 |
154 | //获取第一个元素,如果Stream中的元素没有排序,并行操作中调用可能会随机返回一个。
155 | Optional first = Stream.of(1, 2, 3, 4).findFirst();
156 | System.out.println(first.get());
157 |
158 | //获取Stream中的元素,串行操作中默认是选取第一个元素,并行操作中取到的结果不同。
159 | Optional any = Stream.of(1, 2, 3, 4).findAny();
160 | System.out.println(any.get());
161 |
162 | //limit 和 sql中的limit类似 截断数据
163 | System.out.println("----------------------limit 和sql中的limit类似 截断数据");
164 | System.out.println(list.stream().limit(2).collect(Collectors.toList()).toString());
165 |
166 | //skip 返回一个丢弃原Stream的前N个元素后剩下元素组成的新Stream,如果原Stream中包含的元素个数小于N,那么返回空Stream。 这个是一个非短路操作,因为和limit相关所以放到一起。
167 | System.out.println("----------------------skip 返回一个丢弃原Stream的前N个元素后剩下元素组成的新Stream");
168 | System.out.println(list.stream().skip(2).collect(Collectors.toList()).toString());
169 |
170 |
171 | }
172 |
173 | }
174 |
--------------------------------------------------------------------------------