欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 8新特性2 Stream、新的时间API

程序员文章站 2022-07-05 21:35:57
  lambda 表达式简写。public class Test {public static void main(String[] args) {// 消费型Consumer con = s->System.out.println(s);//简化Consumer con2 = System.out::println;con2.accept(666);// 比较Comparat.....

java 8新特性2 Stream、新的时间API

  lambda 表达式简写。


public class Test {
	public static void main(String[] args) {
		// 消费型
		Consumer<Integer> con = s->System.out.println(s);
		
		//简化
		Consumer<Integer> con2 = System.out::println;
		con2.accept(666);
		
		// 比较
		Comparator<Integer> comparator = new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				return Integer.compare(o1, o2);
			}
		};

		//简化 ::静态方法
		Comparator<Integer> comp = Integer::compare;

		// 函数型
		Function<String, String> function = s->s.toUpperCase();
		
		//简化 ::实例方法
		Function<String, String> function = String::toUpperCase;
		
		// 供给型
		Supplier<String> supplier = ()->new String();
			
		//简化 ::new
		Supplier<String> supplier = String::new;
	}
}

  Stream,类似集合,只不过集合存数据,流存的是操作,处理中间过程。
  创建Stream对象。集合对象调用 stream 和parallelStream 方法;Arrays 接口调用 stream 方法;Stream 接口调用 of、iterate、generate 方法;IntStream 流的创建,IntStream 接口的 of、range、rangeClose 方法。

//
public class Person {
	private String name;
	private int    age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}


public class StreamTest {
	public static void main(String[] args) {
		List<Person> list = new ArrayList<Person>();
		list.add(new Person("张三", 66));
		list.add(new Person("李四", 25));
		list.add(new Person("王五", 25));
		list.add(new Person("赵六", 25));
		
		//forEach :循环打印 1
		list.stream().forEach(System.out::println);

		//多线程打印
		list.parallelStream().forEach(System.out::println);
		
		String[] as = {"zs","ls"};
		//循环打印 2
		Arrays.stream(as).forEach(System.out::println);
		
		// 	循环打印 3
		Stream.of("sunwokong","zhubajie").forEach(System.out::println);
		
		//迭代3次,打印 5 7 9
		Stream.iterate(3, x->x+2).limit(3).forEach(System.out::println);
		
		Stream.generate(()->new Random().nextInt(5)).limit(3).forEach(System.out::println);
	
		//3, 6, 8
		IntStream.of(3,6,8).forEach(System.out::println);
		
		//3, 4
		IntStream.range(3, 5).forEach(System.out::println);
		
		//3, 4, 5
		IntStream.rangeClosed(3, 8).forEach(System.out::println);
	}
}

  中间过程操作,filter、limit、skip,dintinct(重写 hashCode 和 equals),sorted,map(映射),parallel(多线程)。


public class StreamTest2 {
	public static void main(String[] args) {
		
		List<Person> list = new ArrayList<Person>();
		list.add(new Person("张三", 66));
		list.add(new Person("李四", 25));
		list.add(new Person("王五", 25));
		list.add(new Person("赵六", 25));
		list.add(new Person("赵六", 35));
		
		//过滤:filter
		list.stream().filter(p->p.getAge()>30).forEach(System.out::println);
		
		//限制集合个数:limit
		list.stream().limit(3).forEach(System.out::println);
		
		//跳过个数
		list.stream().skip(1).forEach(System.out::println);
		
		//去重:distinct:重写hashCode和equals
		list.stream().distinct().forEach(System.out::println);
		
		//排序
		list.stream().sorted((o1,o2)->o1.getAge()-o2.getAge()).forEach(System.out::println);
		
		//匹配映射规则:map
		list.stream().map(p->p.getName()).forEach(System.out::println);
		
		//多线程执行:parallel
		list.stream().parallel().forEach(System.out::println);
	}
}

  最终结果 forEach、min、max、count、reduce (汇总)、collect (收集-转 List和 Set)。


public class StreamTest3 {
	public static void main(String[] args) {
		
		//获取最小的对象:min
		System.out.println(list.stream().min((o1,o2)->o1.getAge()-o2.getAge()));  
		
		//获取最大的对象:max
		System.out.println(list.stream().max((o1,o2)->o1.getAge()-o2.getAge())); 
		
		//个数
		System.out.println(list.stream().count());  
		
		//reduce:规约,汇总--转成存整数的流,再汇总
		Optional<Integer> o3 = list.stream().map(p->p.getAge()).reduce((o1,o2)->o1+o2);
		// 141
		System.out.println(o3.get());
		
		//collect:收集
		List<String> list2 = list.stream().map(p->p.getName()).collect(Collectors.toList());
		System.out.println(list2);
	}
}

  新的时间 API。
  之前的时间 API 存在着线程不安全,在多线程中用新时间API取代。


public class DateTest {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService es = Executors.newFixedThreadPool(10);
		
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
		
		Callable<LocalDate> callable = new Callable<LocalDate>() {
			@Override
			public LocalDate call() throws Exception { //10个线程
				Thread.sleep(9);
				
				//return sdf.parse("20200703");
				
				return LocalDate.parse("20200703", dtf);  //此处解决线程安全
			}
		};
		List<Future<LocalDate>> list = new ArrayList<>();
		for(int i=0;i<10;i++) {
			Future<LocalDate> future = es.submit(callable);
			list.add(future);
		}
		
		for(Future<LocalDate> future : list) {
			System.out.println(future.get());  //遍历打印
		}
		es.shutdown();
	}
}

  本地化日期时间,LocalDate、LocalTime、LocalDateTime。时间戳,Instant。时区,ZoneId。


public class DateTest2 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// 日期
		LocalDate localDate = LocalDate.now();
		System.out.println(localDate);
		
		// 时间
		LocalTime localTime = LocalTime.now();
		System.out.println(localTime);
		
		// 日期 + 时间
		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println(localDateTime);
		
		System.out.println(localDateTime.getYear());
		
		// 时间戳
		Instant instant = Instant.now();
		System.out.println(instant);
		
		//系统默认时区
		ZoneId zoneId = ZoneId.systemDefault();  
		System.out.println(zoneId);
	}
}

  日期间的格式转换,Date、Instant、LocalDateTime转换。格式化日期类,DateTimeFormat。


public class DateTest3 {
	public static void main(String[] args) {
		// Date->Instant->LocalDateTime
		Date date = new Date();
		Instant instant = date.toInstant();
		System.out.println(instant);
		LocalDateTime ldt = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
		System.out.println(ldt);
		
		// LocalDateTime->Instant->Date
		Instant instant2 = ldt.atZone(ZoneId.systemDefault()).toInstant();
		System.out.println(instant2);
		Date date2 = Date.from(instant2);
		System.out.println(date2);
		
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		String strDate = dateTimeFormatter.format(LocalDateTime.now());
		System.out.println(strDate);
	}
}


本文地址:https://blog.csdn.net/liu1shi/article/details/110825665

相关标签: java 相关 java