JDK1.8新特性

  1 package com.example.jdk8.lambda;
  2 
  3 import org.springframework.core.convert.converter.Converter;
  4 
  5 import java.awt.*;
  6 import java.nio.file.DirectoryStream;
  7 import java.time.*;
  8 import java.time.format.DateTimeFormatter;
  9 import java.time.format.FormatStyle;
 10 import java.time.temporal.ChronoUnit;
 11 import java.util.*;
 12 import java.util.List;
 13 import java.util.concurrent.TimeUnit;
 14 import java.util.function.Function;
 15 import java.util.function.Predicate;
 16 import java.util.stream.Collectors;
 17 import java.util.stream.Stream;
 18 
 19 /**
 20  * @program: jdk8
 21  * @description: 接口的默认方法
 22  * @author: hh.g
 23  * @create: 2019-03-24 10:51:54
 24  */
 25 @FunctionalInterface
 26 interface Formula {
 27     double calculate(int a);
 28 
 29     default double sqrt(int a) {
 30         return Math.sqrt(a);
 31     }
 32 }
 33 
 34 class Something {
 35     String startsWith(String s) {
 36         return String.valueOf(s.charAt(0));
 37     }
 38 }
 39 
 40 class Person {
 41     String firstName;
 42     String lastName;
 43 
 44     public Person() {
 45     }
 46 
 47     public Person(String firstName, String lastName) {
 48         this.firstName = firstName;
 49         this.lastName = lastName;
 50     }
 51 }
 52 
 53 interface PersonFactory<P extends Person> {
 54     P crete(String firstName, String lastName);
 55 }
 56 
 57 
 58 public class Demo04 {
 59 
 60     //Lambda表达式
 61     public static void lambdaSort() {
 62         List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
 63         Collections.sort(names, Comparator.naturalOrder());
 64         names.forEach(i -> System.out.println("i = " + i));
 65     }
 66 
 67     //函数式接口
 68     public static void interfaceMethod() {
 69         Converter<String, Integer> converter1 = Integer::valueOf;
 70         Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
 71         Integer convert = converter.convert("123");
 72         System.out.println(convert);
 73     }
 74 
 75     //引用对象方法
 76     public static void quoteMethod() {
 77         Something something = new Something();
 78         Converter<String, String> startsWith = something::startsWith;
 79         String java = startsWith.convert("Java");
 80         System.out.println("java = " + java);
 81     }
 82 
 83     //调用多个构造参数的函数
 84     public static void test() {
 85         PersonFactory<Person> personPersonFactory = Person::new;
 86         Person crete = personPersonFactory.crete("Java", "Web");
 87 
 88     }
 89 
 90     public static void test02() {
 91         Person person = new Person();
 92         Predicate<String> keyEventDispatcher = (s) -> s.length() > 0;
 93         System.out.println(keyEventDispatcher.test("foo"));
 94         System.out.println(keyEventDispatcher.negate().test("foo"));
 95         Predicate<String> isEmpty = String::isEmpty;
 96         Predicate<Boolean> nonNull = Objects::nonNull;
 97         System.out.println(nonNull.negate());
 98         System.out.println(isEmpty.test(""));
 99 
100 
101     }
102 
103 
104     public static void test03() {
105         Function<String, Integer> formula = Integer::valueOf;
106         Function<String, String> stringStringFunction = formula.andThen(String::valueOf);
107         String apply = stringStringFunction.apply("123");
108         System.out.println(apply);
109     }
110 
111     public static void test04() {
112         List<String> list = new ArrayList<>();
113         list.add("aaaa");
114         list.add("bbbb");
115         list.add("a1a11a");
116         //输出
117         list.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);
118         //排序输出
119         list.stream().sorted().filter(s -> s.startsWith("a")).forEach(System.out::println);
120         //降序
121         list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
122         //Map映射
123         list.stream().map(String::toUpperCase).sorted(Comparator.naturalOrder()).forEach(System.out::println);
124         Stream<String> sorted = list.stream().map(String::toUpperCase).sorted(Comparator.naturalOrder());
125         Set<String> collect = sorted.collect(Collectors.toSet());
126         //Match匹配
127         boolean a = list.stream().anyMatch(s -> s.startsWith("a"));
128         System.out.println("a = " + a);
129         //判断是否全为a开头的
130         System.out.println(list.stream().allMatch(s -> s.startsWith("a")));
131         //判断一个字符在该集合中是否存在
132         System.out.println(list.stream().noneMatch(s -> s.startsWith("z")));
133         System.out.println("==================Count计数=======================");
134         System.out.println("存在的数据有" + list.stream().filter(s -> s.startsWith("a")).count());
135         Optional<String> reduce = list.stream().sorted().reduce((s1, s2) -> s1 + "#" + s2);
136         reduce.ifPresent(System.out::println);
137         //reduce规约
138         String reduce1 = Stream.of("A", "B", "C", "D").reduce("*", String::concat);
139         System.out.println(reduce1);
140 
141     }
142 
143     /**
144      * Parallel Stream 并行流
145      */
146     public static void demo05() {
147         int max = 1000000;
148         List<String> list = new ArrayList<>(max);
149         for (int i = 0; i < max; i++) {
150             UUID uuid = UUID.randomUUID();
151             list.add(uuid.toString());
152         }
153 
154         //串行排序(Sequential)
155         long t0 = System.nanoTime();
156         long count = list.stream().sorted().count();
157         System.out.println("count = " + count);
158         long t1 = System.nanoTime();
159         long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
160         System.out.println(String.format("sequential sort took %d ms", millis));
161 
162         //并行排序(paralel)
163         long fisttime = System.nanoTime();
164         System.out.println(list.parallelStream().sorted().count());
165         long endTime = System.nanoTime();
166         long total = TimeUnit.NANOSECONDS.toMillis(endTime - fisttime);
167         System.out.println(String.format("parallel sort took: %d ms", total));
168 
169     }
170 
171     /**
172      * Maps
173      */
174     public static void demo06() {
175         Map<Integer, String> map = new HashMap<>();
176         for (int i = 0; i < 10; i++) {
177             //如果存在则不往里面存储,不存在则进行存储
178             map.putIfAbsent(i, "val" + i);
179         }
180         //putIfAbsent 阻止我们在null检查时写入额外的代码; forEach接受一个 consumer 来对 map 中的每个元素操作。
181         map.forEach((id, val) -> System.out.println(val));
182         System.out.println("================对map的操作===============");
183         //只对已存在的数据进行操作
184         map.computeIfPresent(3, (num, val) -> val + num);
185         System.out.println(map.get(3));
186 
187         map.computeIfPresent(9, (num, value) -> null);
188         System.out.println(map.containsKey(9));
189         //当该key不存在时才会起作用
190         map.computeIfAbsent(23, num -> "val" + num);
191         System.out.println(map.get(23));
192 
193         map.putIfAbsent(3, "bam");
194         System.out.println(map.get(3));
195 //        此方法不论存不存在都在执行完成后添加
196         map.compute(3,(key,value)->"测试数据");
197         System.out.println(map.get(3));
198 
199 //        接下来展示如何在Map里删除一个键值全部匹配的项
200         //此方法表示,必须键和值都匹配才进行删除
201         map.remove(2,"val2");
202         map.forEach((key,value)-> System.out.println(key+"==="+value));
203         //该方法存在一个默认值,当集合中不存在该键时则返回后面的默认值
204         String not_found = map.getOrDefault(42, "not found");
205         System.out.println("not_found = " + not_found);
206         System.out.println("===========merge方法的使用(合并)");
207 //        对map元素进行合并也变得很容易
208         //merge做的事是如果键名不存在再插入,否则则对原键对应的值做合并操作,重新插入到map中
209         map.merge(9,"val9",(value,newValue)->value.concat(newValue));
210         map.forEach((key,value)-> System.out.println(key+"==="+value));
211         map.merge(9,"concat",(value,newValue)->value.concat(newValue));
212         System.out.println(map.get(9));
213     }
214 
215     /**
216      * Date API 的使用
217      */
218     public static void demo07(){
219         System.out.println("=================Date API================");
220         Clock clock = Clock.systemDefaultZone();
221         long millis = clock.millis();
222         System.out.println("millis = " + millis);
223         Instant instant = clock.instant();
224         System.out.println("instant = " + instant);
225         Date legacyDate = Date.from(instant);
226         System.out.println("legacyDate = " + legacyDate);
227 
228 //        Timezones(时区)
229         System.out.println(ZoneId.getAvailableZoneIds());
230         ZoneId zone1 = ZoneId.of("Europe/Berlin");
231         ZoneId zone2 = ZoneId.of("Brazil/East");
232         System.out.println("zone1.getRules() = " + zone1.getRules());
233         System.out.println("zone2.getRules() = " + zone2.getRules());
234 //        LocalTime(本地时间)
235         LocalTime now1 = LocalTime.now(zone1);
236         LocalTime now2 = LocalTime.now(zone2);
237         System.out.println(now1.isBefore(now2));
238 
239         LocalTime late = LocalTime.of(15, 10, 20);
240         System.out.println("late = " + late);
241         DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMAN);
242         LocalTime parse = LocalTime.parse("13:37", formatter);
243         System.out.println("parse = " + parse);
244 //      LocalDate  本地日期
245         LocalTime now = LocalTime.now();
246         System.out.println("now = " + now);
247         System.out.println("================LocalDate=================");
248         LocalDate today = LocalDate.now();
249         System.out.println("今天的日期 = " + today);
250         LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
251         System.out.println("明天的日期 = " + tomorrow);
252         LocalDate yesterday = today.minusDays(1);
253         System.out.println("昨天的日期 = " + yesterday);
254         LocalDate of = LocalDate.of(2019, Month.MARCH, 24);
255         DayOfWeek dayOfMonth = of.getDayOfWeek();
256         int dayOfMonth1 = of.getDayOfMonth();
257         System.out.println("今天是周几:"+dayOfMonth);
258         System.out.println("今天是"+dayOfMonth1);
259         System.out.println(of.getMonthValue());
260 //      格式化日期
261         String str = "2019-03-24 15时34分40秒";
262         DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH时mm分ss秒");
263         LocalDate parse1 = LocalDate.parse(str, formatter1);
264         System.out.println("parse1 = " + parse1);
265 
266         LocalDateTime now3 = LocalDateTime.now();
267         String format = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(now3);
268         System.out.println("format = " + format);
269         DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
270         System.out.println(dateTimeFormatter.format(now3));
271     }
272 
273 
274 
275     public static void main(String[] args) {
276         //TODO 通过匿名内部类的方式访问接口
277         Formula formula = new Formula() {
278             @Override
279             public double calculate(int a) {
280                 return sqrt(a * 100);
281             }
282         };
283         System.out.println(formula.calculate(100));
284         System.out.println(formula.sqrt(16));
285         lambdaSort();
286         interfaceMethod();
287         quoteMethod();
288         test02();
289         test03();
290         test04();
291         //demo05();
292         demo06();
293         demo07();
294     }
295 }

 

posted @ 2019-03-24 15:48  演绎、白色舞步  阅读(252)  评论(0编辑  收藏  举报