JDK8 部分代码测试

JDK8 部分代码测试


 (p1, p2) -> p1.firstName

()放参数,可不带类型

->  特定

{ } 方法块 或者一行代码;


( int x, int y) -> x + y    //两整形参数,返回它们的和
() -> 42                   //无参数,直接返回 42
x -> 100 ;                  //可推断出参数 x 的类型
(String s) -> { System.out.println(s); } //传入一个字符,只执行一个操作,无返回值

  • “::” 域操作符

JDK8 又重新借用了 C++ 的那个 “::” 域操作符,全称为作用域解析操作符。

  • 测试代码

package com.test.jdk;

import java.time.Clock;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class JDK8Test {

	public static void main(String[] args) {

		 Comparator<Person> comparator = (p1, p2) -> p1.firstName
		 .compareTo(p2.firstName);
		
		 Person p1 = new Person("John", "Doe");
		 Person p2 = new Person("Alice", "Wonderland");
		
		 System.out.println(comparator.compare(p1, p2)); // > 0
		
		 System.out.println(comparator.reversed().compare(p1, p2)); // < 0
		
		 // Function 接口有一个参数并且返回一个结果,
		 // 并附带了一些可以和其他函数组合的默认方法(compose, andThen):
		 Function<String, Integer> toInteger = Integer::valueOf;
		 Function<String, String> backToString = toInteger
		 .andThen(String::valueOf);
		
		 backToString.apply("123"); // "123"
		
		 System.out.println(backToString);
		
		 // Supplier 接口返回一个任意范型的值,和Function接口不同的是该接口没有任何参数
		 Supplier<Object> personSupplier = Object::new;
		 personSupplier.get(); // new Object
		
		 System.out.println(personSupplier.get());
		
		 new Thread(() -> {
		 for (int i = 0; i < 9; i++) {
		 System.out.println(String.format(
		 "Message #%d from inside the thread!", i));
		 }
		 }).start();
		
		 new Thread(() -> {
		 System.out.println(String.format(
		 "Message #%d from inside the thread!", 1024));
		 }).start();
		
		 List inputList = new LinkedList<>();
		 List upper = new LinkedList<>();
		 //有问题u
//		 inputList.stream().filter(x -> (x != null &&
//		 x.matches("[A-Z0-9]*"))).into(upper);
//		
//		 int sumX = inputList.stream()
//		 .filter(x -> (x != null && x.matches("[A-Z0-9]*")))
//		 .map(String::length).reduce(0, Integer::sum);
//		 //从集合中取出每个元素然后打印
//		 List list = new ArrayList<>();
//		 list.add("123aa");
//		 list.add("124aa");
//		 list.add("125aa");
//		 list.forEach(x -> System.out.println(x));
//		 Arrays.asList("Alice", "Bob", "Charlie",
//		 "Dave").forEach(System.out::println);
//		 //names.filter 有问题 啊,,怎么回事啊~!~
//		 List<String> names = Arrays.asList("Alice", "Bob", "Charlie",
//		 "Dave");
//		 List<String> filteredNames = names.filter((e) -> e.length() >= 4)
//		 .into(new ArrayList<String>());
//		
//		 names.filter(e -> e.length() >= 4)
//		 .forEach(x -> System.out.println(x));
		 //并行Streams
		 int max = 1000000;
		 List<String> values = new ArrayList<>(max);
		 for (int i = 0; i < max; i++) {
		 UUID uuid = UUID.randomUUID();
		 values.add(uuid.toString());
		 }
		 //串行排序:
		 long t0 = System.nanoTime();
		
		 long count = values.stream().sorted().count();
		 System.out.println(count);
		
		 long t1 = System.nanoTime();
		
		 long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
		 System.out.println(String.format("sequential sort took: %d ms",
		 millis));
		
		 //并行排序:
		 t0 = System.nanoTime();
		 count = values.parallelStream().sorted().count();
		 System.out.println(count);
		 t1 = System.nanoTime();
		 millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
		 System.out.println(String.format("parallel sort took: %d ms",
		 millis));
		 //DATE API
		// Clock 时钟
		Clock clock = Clock.systemDefaultZone();
		 millis = clock.millis();

		Instant instant = clock.instant();
		Date legacyDate = Date.from(instant); // legacy java.util.Date
		System.out.println(legacyDate);
		
		// Timezones 时区
		System.out.println(ZoneId.getAvailableZoneIds());
		// prints all available timezone ids

		ZoneId zone1 = ZoneId.of("Europe/Berlin");
		ZoneId zone2 = ZoneId.of("Brazil/East");
		System.out.println(zone1.getRules());// ZoneRules[currentStandardOffset=+01:00]
		System.out.println(zone2.getRules());// ZoneRules[currentStandardOffset=-03:00]
		//LocalTime 本地时间
		LocalTime now1 = LocalTime.now(zone1);
		LocalTime now2 = LocalTime.now(zone2);

		System.out.println(now1.isBefore(now2));  // false

		long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
		long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);

		System.out.println(hoursBetween);       
		System.out.println(minutesBetween);     
		LocalTime late = LocalTime.of(23, 59, 59);
		System.out.println(late);       // 23:59:59

		DateTimeFormatter germanFormatter =
		    DateTimeFormatter
		        .ofLocalizedTime(FormatStyle.SHORT)
		        .withLocale(Locale.GERMAN);

		LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
		System.out.println(leetTime);   // 13:37
		//LocalDate 本地日期
		LocalDate today = LocalDate.now();
		LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
		LocalDate yesterday = tomorrow.minusDays(2);

		LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
		DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
		System.out.println(dayOfWeek); // FRIDAY
		//从字符串解析一个LocalDate类型和解析LocalTime一样简单:
		 germanFormatter =
			    DateTimeFormatter
			        .ofLocalizedDate(FormatStyle.MEDIUM)
			        .withLocale(Locale.GERMAN);

		LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
		System.out.println(xmas);   // 2014-12-24
		//LocalDateTime 本地日期时间
		LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);

		 dayOfWeek = sylvester.getDayOfWeek();
		System.out.println(dayOfWeek);      // WEDNESDAY

		Month month = sylvester.getMonth();
		System.out.println(month);          // DECEMBER

		long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
		System.out.println(minuteOfDay);    // 1439
		//只要附加上时区信息,就可以将其转换为一个时间点Instant对象,
		//Instant时间点对象可以很容易的转换为老式的java.util.Date。
		 instant = sylvester
		        .atZone(ZoneId.systemDefault())
		        .toInstant();
		 legacyDate = Date.from(instant);
		System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014
		
		DateTimeFormatter formatter =
			    DateTimeFormatter
			        .ofPattern("MMM dd, yyyy - HH:mm");

		LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
		String string = formatter.format(parsed);
		System.out.println(string);     // Nov 03, 2014 - 07:13
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值