首页 > 技术文章 > JDK8-新特性-附demo

-flq 2018-10-31 14:08 原文

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class test {

	public static void main(String[] args) {
		List<String> stringCollection = new ArrayList<>();
		stringCollection.add("ddd2");
		stringCollection.add("aaa2");
		stringCollection.add("bbb1");
		stringCollection.add("aaa1");
		stringCollection.add("bbb3");
		stringCollection.add("ccc");
		stringCollection.add("bbb2");
		stringCollection.add("ddd1");
		
		/*Filter 过滤
		过滤通过一个predicate接口来过滤并只保留符合条件的元素,该操作属于中间操作,所以我们可以在过滤后的结果来应用其他Stream操作 (比如forEach)。
		forEach需要一个函数来对过滤后的元素依次执行。forEach是一个最终操作,所以我们不能在forEach之后来执行 其他Stream操作。*/
		stringCollection
		 .stream()
		 .filter((s) -> s.startsWith("a"))
		 .forEach(System.out::println);
		System.out.println("--------1------");
		/*Sort 排序

		排序是一个中间操作,返回的是排序好后的Stream。如果你不指定一个自定义的Comparator则会使用默认排序。
		倒叙
		*/
		stringCollection
		.stream()
		.filter((s) -> s.startsWith("a"))
		.sorted(Comparator.reverseOrder())
		.collect(Collectors.toList())
		.forEach(a ->{
			System.out.println(a.toString());
		});
		
		
		System.out.println("-------2-------");
		//正序
		stringCollection
		.stream()
		.filter((s) -> s.startsWith("a"))
		.sorted()
		.forEach(a ->{
			System.out.println(a.toString());
		});
		
		System.out.println("-------3-------");
		
	/*	Map 映射
		中间操作map会将元素根据指定的Function接口来依次将元素转成另外的对象,
		下面的示例展示了将字符串转换为大写字符串。你也可以通过map来讲对象转换成其他类型,map返回的Stream类型是根据你map传递进去的函数的返回值决定的。*/
		
		stringCollection
		.stream()
		.map(String :: toUpperCase)//大写
		.map(String :: toLowerCase)//小写
		.sorted((a, b) ->b.compareTo(a))
		.forEach(System.out::println);
		
		
		System.out.println("-------4-------");
		/*Match 匹配

		Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。所有的匹配操作都是最终操作,并返回一个boolean类型的值。*/
		boolean anyMatch = stringCollection
		.stream()
		.anyMatch((a) -> a.startsWith("a"));
		
		System.out.println(anyMatch);
		
		boolean allStartsWithA = 
				 stringCollection
				 .stream()
				 .allMatch((s) -> s.startsWith("a"));

				System.out.println(allStartsWithA);      // false

		boolean noneStartsWithZ = 
		 stringCollection
		 .stream()
		 .noneMatch((s) -> s.startsWith("z"));

		System.out.println(noneStartsWithZ);      // true
		
		
		
		System.out.println("------5------");
		/*对两个 List 遍历匹配数据的优化处理*/
		List<Map<Object, Object>> list1 = new ArrayList<>();
		List<Map<Object, Object>> list2 = new ArrayList<>();
		List<Map<Object, Object>> list3 = list1.stream()
	                .map(map -> list2.stream()
	                                .filter(m -> Objects.equals(m.get("id"), map.get("id")))
	                                .findFirst().map(m -> {
	                                    map.putAll(m);
	                                    return map;
	                                }).orElse(null))
	                .filter(Objects::nonNull).collect(Collectors.toList());
		
		
		
		//count
		long l = stringCollection
		.stream()
		.sorted()
		.filter((a) ->a.startsWith("a"))
		.count();
		System.out.println(l);
		
		System.out.println("------6------");

		
//		并行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));
		// 串行耗时: 899 ms
		
		long t01 = System.nanoTime();
		long count1 = values.parallelStream().sorted().count();
		System.out.println(count1);

		long t11 = System.nanoTime();

		long millis1 = TimeUnit.NANOSECONDS.toMillis(t11 - t01);
		System.out.println(String.format("parallel sort took: %d ms", millis1));

		// 并行排序耗时: 472 ms
		
		System.out.println("------7------");

		/*Map

		前面提到过,Map类型不支持stream,不过Map提供了一些新的有用的方法来处理一些日常任务。*/
		Map<Integer, String> map = new HashMap<>();
		for (int i = 0; i < 10; i++) {
		 map.putIfAbsent(i, "val" + i);
		}
		map.forEach((id, val) ->
		System.out.println(val));
		
		
		
		System.out.println("-------8--------");
		
		/*新增base64加解密API*/
		final String text = "就是要测试加解密!!abjdkhdkuasu!!@@@@";
		       String encoded = Base64.getEncoder()
		           .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
		       System.out.println("加密后="+ encoded );
		        
		       final String decoded = new String( 
		           Base64.getDecoder().decode( encoded ),
		           StandardCharsets.UTF_8 );
		       System.out.println( "解密后="+decoded );
		       
		       
		       
		System.out.println("-------9--------");
		

		
	}
}

  

推荐阅读