Java1.8 new features study notes

The Collections class in Java 1.8 has many enhancements. You can directly call the serial Collections.stream() or the parallel Collections.parallelStream() to process and operate the data in the List and Set (Map is not supported).

1: What is stream ?

    java.util.Stream is an interface that was introduced in 1.8. It represents the sequence of an atom, and various operations can be performed on the atom. Stream can be an intermediate operation or the heaviest operation. Returns the stream object itself as an intermediate operation, or a value of some type as the heaviest operation. Action methods can be called multiple times on this stream as an intermediate operation.

2: lambda expressions

In fact, a lambda expression is essentially an anonymous function, which consists of three parts: a parameter list, an arrow (->), and an expression or statement block. Let's see an example:

public void sum(int a, int b){
    return a+b;
}

Converted to a lambda expression as

(int a, int b) -> a + b;

It can also be written like this, because java will infer the parameter type based on the context

(a, b) -> {return a + b;}

or

(a, b) -> a + b;

3: Concrete example

package cn.huiyunche.driver.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;

public class Lambda {
	private static List<String> lambdaList = new ArrayList<>();
	
	private static String string = "string";
	private static String integer = "integer";
	
	public Lambda() {
		initData(string);
	}
	
	public static void initData(String flag) {
		if (CollectionUtils.isNotEmpty(lambdaList)) {
			lambdaList.clear();
		}
		if (string.equals(flag)) {
			lambdaList.add("Ulrica");
			lambdaList.add("Quella");
			lambdaList.add("Cecilia");
			lambdaList.add("Claudia");
			lambdaList.add("Desdemona");
			lambdaList.add("Indira");
		} else {
			lambdaList.add("1");
			lambdaList.add("2");
			lambdaList.add("2");
			lambdaList.add("3");
			lambdaList.add("3");
			lambdaList.add("4");
			lambdaList.add("4");
			lambdaList.add("4");
			lambdaList.add("5");
			lambdaList.add("5");
			lambdaList.add("5");
			lambdaList.add("6");
			lambdaList.add("6");
		}
	}
	
	// 这种方式就不多讲了,以前旧版本比较常见的做法
	public static void runThreadUseInnerClass() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("内部类实现的线程");
            }
        }).start();
    }
	
	// 新版本写法
	public static void thred() {
		new Thread(() -> System.out.println("内部类实现的线程")).start();
	}
	
	// 遍历list
	public static void ergodicList() {
		initData(string);
		System.out.println("=================遍历list开始==========>>>>>>>>>>>");
		lambdaList.forEach((value) -> System.out.println("value = " + value));
		System.out.println("<<<<<<<<<<<======遍历list结束=====================");
	}
	
	// 正序排序list
	public static void asc() {
		initData(integer);
		System.out.println("=================正序排序list开始==========>>>>>>>>>>>");
		lambdaList.stream().sorted().forEach((value) -> System.out.println("value = " + value));
		System.out.println("=================正序排序list结束==========>>>>>>>>>>>");
	}
	
	// 倒序排序list
	public static void desc() {
		initData(integer);
		System.out.println("=================倒序排序list开始==========>>>>>>>>>>>");
		lambdaList.stream().sorted((a, b) -> b.compareTo(a)).forEach((value) -> System.out.println("value = " + value));
		System.out.println("=================倒序排序list结束==========>>>>>>>>>>>");
	}
	
	// 过滤
	public static void filter(String val) {
		initData(string);
		System.out.println("=================过滤开始==========>>>>>>>>>>>");
		lambdaList.stream().filter((value) -> value.toLowerCase().contains(val.toLowerCase())).forEach((value) -> System.out.println("value = " + value));
		System.out.println("=================过滤结束==========>>>>>>>>>>>");
	}
	
	// map使用
	public static void map() {
		initData(string);
		System.out.println("=================map使用开始==========>>>>>>>>>>>");
		//lambdaList.stream().map((value) -> value.toUpperCase()).forEach((value) -> System.out.println("value = " + value));
		lambdaList.stream().map(String::toUpperCase).forEach((value) -> System.out.println("value = " + value));
		System.out.println("=================map使用结束==========>>>>>>>>>>>");
	}
	
	//parallelStream (并行) 和 stream(串行)
	public static void stream() {
		System.out.println("=================parallelStream (并行) 和 stream(串行)开始==========>>>>>>>>>>>");
		int max = 1000000;
		long t0, t1, count, millis;
		List<String> list = new ArrayList<>(max);
		for (int i = 0; i < max; i++) {
			UUID uuid = UUID.randomUUID();
			list.add(uuid.toString());
		}
		// 串行
		t0 = System.nanoTime();
		count = list.stream().sorted().count();
		System.out.println("count = " + count);
		t1 = System.nanoTime();
		millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
		System.out.println(String.format("串行排序耗时: %d ms", millis));
		
		System.out.println("===========================");
		
		long t00, t11, count0, millis0;
		List<String> list0 = new ArrayList<>(max);
		for (int i = 0; i < max; i++) {
			UUID uuid = UUID.randomUUID();
			list0.add(uuid.toString());
		}
		// 串行
		t00 = System.nanoTime();
		count0 = list0.stream().sorted().count();
		System.out.println("count0 = " + count0);
		t11 = System.nanoTime();
		millis0 = TimeUnit.NANOSECONDS.toMillis(t11 - t00);
		System.out.println(String.format("并行排序耗时: %d ms", millis0));
		
		System.out.println("===========================");
		
		long millis00;
		millis00 = TimeUnit.NANOSECONDS.toMillis((t1 - t0) - (t11 - t00));
		System.out.println(String.format("串行比并行排序多耗时: %d ms", millis00));
		
		System.out.println("=================parallelStream (并行) 和 stream(串行)结束==========>>>>>>>>>>>");
	}
	
	// noneMatch
	public static void noneMatch(String val) {
		System.out.println("=================noneMatch使用开始==========>>>>>>>>>>>");
		initData(string);
		boolean bool = lambdaList.stream().noneMatch((value) -> value.contains(val));
		System.out.println("contains bool = " + bool);
		bool = lambdaList.stream().noneMatch((value) -> value.endsWith(val));
		System.out.println("endsWith bool = " + bool);
		bool = lambdaList.stream().noneMatch((value) -> value.startsWith(val));
		System.out.println("startsWith bool = " + bool);
		System.out.println("=================noneMatch使用结束==========>>>>>>>>>>>");
		
	}
	
	// allMatch
	public static void allMatch(String val) {
		System.out.println("=================allMatch使用开始==========>>>>>>>>>>>");
		initData(string);
		boolean bool = lambdaList.stream().allMatch((value) -> value.startsWith(val));
		System.out.println("bool = " + bool);
		System.out.println("=================allMatch使用结束==========>>>>>>>>>>>");
		
	}
	
	// anyMatch
	public static void anyMatch(String val) {
		System.out.println("=================anyMatch使用开始==========>>>>>>>>>>>");
		initData(string);
		boolean bool = lambdaList.stream().anyMatch((value) -> value.matches(val));
		System.out.println("bool = " + bool);
		System.out.println("=================anyMatch使用结束==========>>>>>>>>>>>");
		
	}
	
	// collect(过滤数据,返回List)
	public static void collect(String val) {
		System.out.println("=================collect使用开始==========>>>>>>>>>>>");
		initData(string);
		List<String> lists = lambdaList.stream().filter((value) -> value.toLowerCase().contains(val.toLowerCase())).collect(Collectors.toList());
		System.out.println(String.format("lists.size: %d ", lists.size()));
		lists.forEach((value) -> System.out.println("value = " + value));
		System.out.println("=================collect使用结束==========>>>>>>>>>>>");
		
	}
	
	// reduce(拼接数据只返回一个结果集)
	public static void reduce() {
		System.out.println("=================reduce使用开始==========>>>>>>>>>>>");
		initData(string);
		lambdaList.stream().reduce((value1, value2) -> value1 + value2).ifPresent(System.out::println);
		System.out.println("=================reduce使用结束==========>>>>>>>>>>>");
		
	}
	
	// 统计大于2小于5
	public static void groupBysum() {
		System.out.println("=================统计大于2小于5使用开始==========>>>>>>>>>>>");
		initData(integer);
		lambdaList.parallelStream().map(Integer::new).filter(val -> val >= 2 && val <= 6).collect(Collectors.groupingBy(p -> new Integer(p), Collectors.summingInt(p -> p))).forEach((key, value) -> System.out.println("key = " + key + " value = " +value));
		System.out.println("=================统计大于2小于5使用结束==========>>>>>>>>>>>");
	}
	
	public static void main(String[] args) {
		thred();
		runThreadUseInnerClass();
		ergodicList();
		asc();
		desc();
		filter("c");
		map();
		stream();
		noneMatch("Claudia");
		allMatch("U");
		anyMatch("Claudia");
		collect("c");
		reduce();
		groupBysum();
	}

}

output result

内部类实现的线程
内部类实现的线程
=================遍历list开始==========>>>>>>>>>>>
value = Ulrica
value = Quella
value = Cecilia
value = Claudia
value = Desdemona
value = Indira
<<<<<<<<<<<======遍历list结束=====================
=================正序排序list开始==========>>>>>>>>>>>
value = 1
value = 2
value = 3
value = 4
value = 4
value = 4
value = 5
value = 6
=================正序排序list结束==========>>>>>>>>>>>
=================倒序排序list开始==========>>>>>>>>>>>
value = 6
value = 6
value = 5
value = 4
value = 3
value = 2
value = 1
=================倒序排序list结束==========>>>>>>>>>>>
=================过滤开始==========>>>>>>>>>>>
value = Ulrica
value = Cecilia
value = Claudia
=================过滤结束==========>>>>>>>>>>>
=================map使用开始==========>>>>>>>>>>>
value = ULRICA
value = QUELLA
value = CECILIA
value = CLAUDIA
value = DESDEMONA
value = INDIRA
=================map使用结束==========>>>>>>>>>>>
=================parallelStream (并行) 和 stream(串行)开始==========>>>>>>>>>>>
count = 1000000
串行排序耗时: 826 ms
===========================
count0 = 1000000
并行排序耗时: 781 ms
===========================
串行比并行排序多耗时: 44 ms
=================parallelStream (并行) 和 stream(串行)结束==========>>>>>>>>>>>
=================noneMatch使用开始==========>>>>>>>>>>>
contains bool = false
endsWith bool = false
startsWith bool = false
=================noneMatch使用结束==========>>>>>>>>>>>
=================allMatch使用开始==========>>>>>>>>>>>
bool = false
=================allMatch使用结束==========>>>>>>>>>>>
=================anyMatch使用开始==========>>>>>>>>>>>
bool = true
=================anyMatch使用结束==========>>>>>>>>>>>
=================collect使用开始==========>>>>>>>>>>>
lists.size: 3 
value = Ulrica
value = Cecilia
value = Claudia
=================collect使用结束==========>>>>>>>>>>>
=================reduce使用开始==========>>>>>>>>>>>
UlricaQuellaCeciliaClaudiaDesdemonaIndira
=================reduce使用结束==========>>>>>>>>>>>
=================统计大于2小于5使用开始==========>>>>>>>>>>>
key = 2 value = 4
key = 3 value = 6
key = 4 value = 12
key = 5 value = 15
key = 6 value = 12
=================统计大于2小于5使用结束==========>>>>>>>>>>>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325822462&siteId=291194637