(一)optional类
创建一个空Optional对象
输出的是一个空的
optional
对象Optional optional = Optional.empty();
System.out.println(optional);
##:Optional.empty创建一个非空Optional对象
如果
person
是null
,将会立即抛出,而不是访问person
的属性时获得一个潜在的错误Person person = new Person("xu","hua");
Optional optional2 = Optional.of(person);
System.out.println(optional2);
System.out.println(optional2.get());
System.out.println(optional2.get().firstName);
##:Optional[xuhua]
xuhua
xu判断对象是否存在
System.out.println(optional.isPresent());
System.out.println(optional2.isPresent());
##:false
true如果Optional为空返回默认值
System.out.println(optional.orElse("fallback"));
optional.ifPresent(System.out::println);
##:fallback
xuhua
(二)Lambda表达式
Lambda表达式的使用
java8以前的字符串排列,创建一个匿名的比较器对象
Comparator
然后将其传递给sort
方法
```
List names= Arrays.asList("peter", "anna", "mike", "xenia");
Collections.sort(names, new Comparator() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
```
`java8`使用`lambda`表达式就不需要匿名对象了
```
Collections.sort(names,(String a,String b)->{return b.compareTo(a);});
```
简化一下:对于函数体只有一行代码的,你可以去掉大括号{}以及`return`关键字
```
Collections.sort(names,(String a,String b)->b.compareTo(a));
```
`Java`编译器可以自动推导出参数类型,所以你可以不用再写一次类型
```
Collections.sort(names, (a, b) -> b.compareTo(a));
```
```
##:[xenia, peter, mike, anna]
```
对于`null`的处理
```
List names2 = Arrays.asList("peter", null, "anna", "mike", "xenia");
names2.sort(Comparator.nullsLast(String::compareTo));
System.out.println(names2);
##:[anna, mike, peter, xenia, null]
```
函数式接口,方法,构造器
每一个
lambda
表达式都对应一个类型,通常是接口类型。而“函数式接口”是指仅仅只包含一个抽象方法的接口,每一个该类型的
lambda
表达式都会被匹配到这个抽象方法。因为默认方法不算抽象方法,所以你也可以给你的函数式接口添加默认方法。
我们可以将
lambda
表达式当作任意只包含一个抽象方法的接口类型,确保你的接口一定达到这个要求,你只需要给你的接口添加
@FunctionalInterface
注解,编译器如果发现你标注了这个注解的接口有多于一个抽象方法的时候会报错的。
函数式接口
@FunctionalInterface
public static interface Converter {
T convert(F from);
}
Converter integerConverter1 = new Converter() {
@Override
public Integer convert(String from) {
return Integer.valueOf(from);
}
};
Converter integerConverter2 = (from) -> Integer.valueOf(from);
Integer converted1 = integerConverter1.convert("123");
Integer converted2 = integerConverter2.convert("123");
System.out.println(converted1);
System.out.println(converted2);
##:123
123
Converter integerConverter3 = Integer::valueOf;
Integer converted3 = integerConverter3.convert("123");
System.out.println(converted3);
##:123函数式方法
static class Something {
String startsWith(String s) {
return String.valueOf(s.charAt(0));
}
}
Something something = new Something();
Converter stringConverter = something::startsWith;
String converted4 = stringConverter.convert("Java");
System.out.println(converted4);
##:j函数式构造器
Java编译器会自动根据PersonFactory.create方法的签名来选择合适的构造函数。
public class Person {
public String firstName;
public String lastName;
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String toString(){
return firstName+lastName;
}
}interface PersonFactory
{
P create(String firstName, String lastName);
}
PersonFactory personFactory = Person::new;
Person person = personFactory.create("xu", "hua");
System.out.println(person.toString());
##:xuhua
Lambda作用域
点一点链接,支持一波吃饭,http://aliyun.guan2ye.com/在lambda表达式中访问外层作用域和老版本的匿名对象中的方式很相似。
你可以直接访问标记了final的外层局部变量,或者实例的字段以及静态变量。
static int outerStaticNum = 10;
int outerNum;
void testScopes() {
int num = 1;
Lambda2.Converter stringConverter =
(from) -> String.valueOf(from + outerStaticNum+num);
String convert = stringConverter.convert(2);
System.out.println(convert);
##:13
Lambda2.Converter stringConverter2 = (from) -> {
outerNum = 13;
return String.valueOf(from + outerNum);
};
System.out.println(stringConverter2.convert(2));
System.out.println("\nBefore:outerNum-->" + outerNum);
outerNum = 15;
System.out.println("After:outerNum-->" + outerNum);
##:Before:outerNum-->13
After:outerNum-->15
String[] array = new String[1];
Lambda2.Converter stringConverter3 = (from) -> {
array[0] = "Hi here";
return String.valueOf(from);
};
stringConverter3.convert(23);
System.out.println("\nBefore:array[0]-->" + array[0]);
array[0] = "Hi there";
System.out.println("After:array[0]-->" + array[0]);
##:Before:array[0]-->Hi here
After:array[0]-->Hi there
}
(三)Stream类
点一点链接,支持一波吃饭,http://aliyun.guan2ye.com/
java.util.Stream
表示能应用在一组元素上一次执行的操作序列。
Stream
操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回Stream
本身,这样你就可以将多个操作依次串起来。
Stream
的创建需要指定一个数据源,比如 java.util.Collection
的子类,List
或者Set
,Map
不支持。
Stream
的操作可以串行执行或者并行执行。
Stream的基本接口
List 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 过滤.
Filter
通过一个predicate
接口来过滤并只保留符合条件的元素,该操作属于中间操作,所以我们可以在过滤后的结果来应用其他Stream
操作(比如forEach
)。forEach
需要一个函数来对过滤后的元素依次执行。forEac
h是一个最终操作,所以我们不能在forEach
之后来执行其他Stream
操作。stringCollection
.stream()
.filter((s) -> s.startsWith("a"))
.forEach(System.out::println);Sorted 排序.
Sorted
是一个中间操作,返回的是排序好后的Stream
。如果你不指定一个自定义的
Comparator
则会使用默认排序.stringCollection
.stream()
.sorted()
.forEach(System.out::println);
System.out.println(stringCollection);Map.
中间操作
ma
p会将元素根据指定的Function
接口来依次将元素转成另外的对象.stringCollection
.stream()
.map(String::toUpperCase)
.map((s)->s+" space")
.sorted((a, b) -> b.compareTo(a))
.forEach(System.out::println);Match
Stream
提供了多种匹配操作,允许检测指定的Predicate
是否匹配整个Stream
。所有的匹配操作都是最终操作,并返回一个boolean类型的值。
boolean anyStartsWithA = stringCollection
.stream()
.anyMatch((s) -> s.startsWith("a"));
System.out.println(anyStartsWithA);
boolean allStartsWithA = stringCollection
.stream()
.allMatch((s) -> s.startsWith("a"));
System.out.println(allStartsWithA);
boolean noneStartsWithZ = stringCollection
.stream()
.noneMatch((s) -> s.startsWith("z"));
System.out.println(noneStartsWithZ);Count
计数是一个最终操作,返回
Stream
中元素的个数,返回值类型是long
。long startsWithB = stringCollection
.stream()
.filter((s) -> s.startsWith("b"))
.count();
System.out.println(startsWithB);Reduce
Reduce
是一个最终操作,允许通过指定的函数来讲stream
中的多个元素规约为一个元素,规约后的结果是通过Optional
接口表示的。Optional reduced =
stringCollection
.stream()
.sorted()
.reduce((s1, s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println);
##:aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2
并行stream和串行stream
串行stream
List 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));并行stream
并行
stream
是在运行时将数据划分成了多个块,然后将数据块分配给合适的处理器去处理。只有当所有块都处理完成了,才会执行之后的代码。
List 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.parallelStream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("parallel sort took: %d ms", millis));时间结果比较:
1000000
sequential sort took: 717 ms
1000000
parallel sort took: 303 ms
IntStream接口
IntStream
接口是stream
的一种,继承了BaseStream
接口。range
IntStream.range(0, 10)
.forEach(i -> {
if (i % 2 == 1) System.out.print(i+" ");
});
##:1 3 5 7 9
OptionalInt reduced1 =
IntStream.range(0, 10)
.reduce((a, b) -> a + b);
System.out.println(reduced1.getAsInt());
int reduced2 =
IntStream.range(0, 10)
.reduce(7, (a, b) -> a + b);
System.out.println(reduced2);
##:45
52sum
System.out.println(IntStream.range(0, 10).sum());
Stream的应用
Map unsortMap = new HashMap<>();
unsortMap.put("z", 10);
unsortMap.put("b", 5);
unsortMap.put("a", 6);
unsortMap.put("c", 20);
unsortMap.put("d", 1);
unsortMap.put("e", 7);
unsortMap.put("y", 8);
unsortMap.put("n", 99);
unsortMap.put("j", 50);
unsortMap.put("m", 2);
unsortMap.put("f", 9);使用
stream
类来对map
的value
排序public static > Map sortByValue(Map map) {
Map result = new LinkedHashMap<>();
map.entrySet().parallelStream()
.sorted((o1, o2) -> (o2.getValue()).compareTo(o1.getValue()))
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
return result;
}
System.out.println(sortByValue(unsortMap));
##:{n=99, j=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}List list = new ArrayList<>();
JSONObject data1 = new JSONObject();
data1.put("type", "支出");
data1.put("money", 500);
JSONObject data2 = new JSONObject();
data2.put("type", "收入");
data2.put("money", 1000);
JSONObject data3 = new JSONObject();
data3.put("type", "借贷");
data3.put("money", 100);
list.add(data1);
list.add(data2);
list.add(data3);使用
stream
类来处理list``里面的
json`数据
list.stream()
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
.sorted((b, a) -> Integer.valueOf(JSONObject.fromObject(a).getInt("money")).compareTo(JSONObject.fromObject(b)
.getInt("money")))
.forEach(System.out::println);
Integer min = list.stream()
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
.map(x -> JSONObject.fromObject(x).getInt("money"))
.sorted()
.findFirst()
.get();
System.out.println(min);
Map type_count = new HashMap<>();
list.stream()
.filter(x -> JSONObject.fromObject(x).containsKey("type"))
.map(x -> JSONObject.fromObject(x).getString("type"))
.forEach(x -> {
if (type_count.containsKey(x)) type_count.put(x, type_count.get(x) + 1);
else type_count.put(x, 1);
});
System.out.println(type_count.toString());
##:
{"type":"收入","money":1000}
{"type":"支出","money":500}
{"type":"借贷","money":100}
100
{借贷=1, 收入=1, 支出=1}
点一点链接,支持一波吃饭,http://aliyun.guan2ye.com/
函数式接口
只包含一个抽象方法的接口
Function
接受一个输入参数,返回一个结果。
Function接口包含以下方法:
定义两个比较简单的函数:
times2
和squared
Function times2 = e -> e * 2;
Function squared = e -> e * e;R apply(T t)
执行函数
Integer a = times2.apply(4);
System.out.println(a);compose
先执行参数里面的操作,然后执行调用者
Integer b = times2.compose(squared).apply(4);
System.out.println(b);andThen
先执行调用者操作,再执行参数操作
Integer c = times2.andThen(squared).apply(4);
System.out.println(c);identity
总是返回传入的参数本身
Integer d = identity.apply(4);
System.out.println(d);
BiFunction
接受输入两个参数,返回一个结果
R apply(T t, U u)
BiFunction add = (x, y) -> x + y;
System.out.println(add.apply(10,20));
Supplier
无参数,返回一个结果。
T get()
Supplier get= () -> 10;
Integer a=get.get();
Consumer
代表了接受一个输入参数并且无返回的操作
void accept(T t)
Consumer accept=x->{};
BiConsumer
代表了一个接受两个输入参数的操作,并且不返回任何结果
void accept(T t, U u)
BiConsumer accept=(x,y)->{};
BinaryOperator extends BiFunction
一个作用于于两个同类型操作符的操作,并且返回了操作符同类型的结果
定义了两个静态方法:
minBy
,maxBy
Predicate
接受一个输入参数,返回一个布尔值结果。
test
Predicate predicate=x->x.startsWith("a");
System.out.println(predicate.test("abc"));
Stream接口
Collector接口
Collector是Stream的可变减少操作接口
Collector接受三个泛型参数,对可变减少操作的数据类型作相应限制:
T:输入元素类型
A:缩减操作的可变累积类型(通常隐藏为实现细节)
R:可变减少操作的结果类型
Collector接口声明了4个函数,这四个函数一起协调执行以将元素目累积到可变结果容器中,并且可以选择地对结果进行最终的变换:
在Collector接口的characteristics方法内,可以对Collector声明相关约束:
CONCURRENT:表示此收集器支持并发,意味着允许在多个线程中,累加器可以调用结果容器
UNORDERED:表示收集器并不按照Stream中的元素输入顺序执行
IDENTITY_FINISH:表示finisher实现的是识别功能,可忽略。
Set characteristics()
:Characteristics是Collector内的一个枚举类,声明了CONCURRENT、UNORDERED、IDENTITY_FINISH等三个属性,用来约束Collector的属性:
如果一个容器仅声明CONCURRENT属性,而不是UNORDERED属性,那么该容器仅仅支持无序的Stream在多线程中执行。
Supplier supplier()
: 创建新的结果结BiConsumer accumulator()
: 将元素添加到结果容器BinaryOperator combiner()
: 将两个结果容器合并为一个结果容器Function finisher()
: 对结果容器作相应的变换
定义自己的Stream
collect
collect
有两个接口:R collect(Supplier supplier,
BiConsumer accumulator,
BiConsumer combiner); R collect(Collector super T, A, R> collector);toList
stringCollection.stream()
.filter(x -> x.startsWith("a")).collect(Collectors.toList())toSet
stringCollection.stream()
.filter(x -> x.startsWith("a")).collect(Collectors.toSet())toCollection
接口:
public static > Collector toCollection(Supplier collectionFactory)
实现:
List list = stringCollection.stream()
.filter(x -> x.startsWith("a"))
.collect(Collectors.toCollection(ArrayList::new));toMap
接口:
public static
Collector> toMap(Function super T, ? extends K> keyMapper,
Function super T, ? extends U> valueMapper)实现:
Function xu = x -> x + "_xu";
Map map = stringCollection.stream()
.filter(x -> x.startsWith("a"))
.distinct()
.collect(Collectors.toMap(Function.identity(), xu));averagingDouble
:求平均值,Stream的元素类型为doubleaveragingInt
:求平均值,Stream的元素类型为intaveragingLong
:求平均值,Stream的元素类型为longcounting
:Stream的元素个数maxBy
:在指定条件下的,Stream的最大元素minBy
:在指定条件下的,Stream的最小元素reducing
: reduce操作summarizingDouble
:统计Stream的数据(double)状态,其中包括count,min,max,sum和平均。summarizingInt
:统计Stream的数据(int)状态,其中包括count,min,max,sum和平均。summarizingLong
:统计Stream的数据(long)状态,其中包括count,min,max,sum和平均。summingDouble
:求和,Stream的元素类型为doublesummingInt
:求和,Stream的元素类型为intsummingLong
:求和,Stream的元素类型为longpartitioningBy
接口:
public static Collector>> partitioningBy(Predicate super T> predicate)
public static
Collector> partitioningBy(Predicate super T> predicate,
Collector super T, A, D> downstream)实现:
Predicate startA = x -> x.startsWith("a");
//return {false=[ddd2, bbb1], true=[aaa1, aaa1]}
Map> map2 = stringCollection.stream()
.collect(Collectors.partitioningBy(startA));
//return {false={false=[ddd2], true=[bbb1]}, true={false=[], true=[aaa1, aaa1]}}
Predicate end1 = x -> x.endsWith("1");
Map>> map3 = stringCollection.stream()
.collect(Collectors.partitioningBy(startA, Collectors.partitioningBy(end1)));groupingBy
接口:
public static Collector>> groupingBy(Function super T, ? extends K> classifier)
public static
Collector> groupingBy(Function super T, ? extends K> classifier,
Collector super T, A, D> downstream)
public static >
Collector groupingBy(Function super T, ? extends K> classifier,Supplier mapFactory,
Collector super T, A, D> downstream)实现:
Function stringStart = x -> String.valueOf(x.charAt(0));
Map> map4 = stringCollection.stream()
.collect(Collectors.groupingBy(stringStart));
Map map5 = stringCollection.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map map6 = stringCollection.stream()
.collect(Collectors.groupingBy(stringStart, LinkedHashMap::new, Collectors.counting()));<1> R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
Supplier supplier是一个工厂函数,用来生成一个新的容器;
BiConsumer accumulator也是一个函数,用来把Stream中的元素添加到结果容器中;
BiConsumer combiner还是一个函数,用来把中间状态的多个结果容器合并成为一个(并发的时候会用到)
Supplier> supplier = ArrayList::new;
BiConsumer, String> accumulator = List::add;
BiConsumer, List> combiner = List::addAll;
List list1 = stringCollection.stream()
.filter(x -> x.startsWith("a"))
.collect(supplier, accumulator, combiner);<2> R collect(Collector super T, A, R> collector)
Collectors
是Java已经提供好的一些工具方法:List stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa1");
stringCollection.add("bbb1");
stringCollection.add("aaa1");转换成其他集合:
转成值:
数据分区:
数据分组:
reduce
reduce
有三个接口:Optional reduce(BinaryOperator accumulator); U reduce(U identity,
BiFunction accumulator,
BinaryOperator combiner);
T reduce(T identity, BinaryOperator accumulator);<1> Optional reduce(BinaryOperator accumulator)
BinaryOperator binaryOperator = (x, y) -> x + y;
String reduceStr1 = stringCollection.stream().reduce(binaryOperator).orElse("");<2> T reduce(T identity, BinaryOperator accumulator)
String reduceStr2=stringCollection.stream().reduce("start:",binaryOperator);<3> U reduce(U identity,BiFunction accumulator,BinaryOperator combiner)
第一个参数返回实例u,传递你要返回的U类型对象的初始化实例u
BiFunction accumulator,负责数据的累加
BinaryOperator combiner,负责在并行情况下最后合并每个reduce线程的结果
List personList = new ArrayList<>();
personList.add(new Person(10, 20));
personList.add(new Person(20, 30));
personList.add(new Person(30, 50));
BiFunction biFunction = (x, y) -> new Person(x.getAge() + y.getAge(), x.getRate() + y.getRate());
BinaryOperator binaryOperator1 = (x, y) -> new Person(x.getAge() + y.getAge(), x.getRate() + y.getRate());
Person total = personList.stream().reduce(new Person(0, 0), biFunction, binaryOperator1);
System.out.println("total:"+total);
Map的双重循环
Map map = new HashMap<>();
crowdMap.entrySet().stream()
.map(Map.Entry::getValue)
.forEach(x -> x.entrySet().forEach(y -> {
if (map.containsKey(y.getKey()))
map.put(y.getKey(), map.get(y.getKey()) + y.getValue());
else map.put(y.getKey(), y.getValue());
}));
Map map = new HashMap<>();
crowdMap.entrySet().stream()
.map(Map.Entry::getValue)
.flatMap(x -> x.entrySet().stream())
.forEach(y -> {
if (map.containsKey(y.getKey()))
map.put(y.getKey(), map.get(y.getKey()) + y.getValue());
else map.put(y.getKey(), y.getValue());
});
Map map = new HashMap<>();
crowdMap.forEach((key, value) -> value.forEach((x, y) -> {
if (map.containsKey(x))
map.put(x, map.get(x) + y);
map.put(x, y);
}));List的多次分组
Map> detailMap = approveRuleDetailList.stream()
.collect(Collectors
.groupingBy(ApproveRuleDetail::getItem, Collectors.
groupingBy(ApproveRuleDetail::getDetail, Collectors.counting())));List按照自定义条件分组
Function ageGroup = x -> x / 10;
Map> ageMap = statisticsPipelineList
.stream()
.collect(Collectors.groupingBy(y -> ageGroup.apply(y.getAge())));
Function ageCredit = x -> {
if (x <= 18)
return 18;
else if (x >= 40)
return 40;
else return x;
};
ToDoubleFunction mapper = StatisticsPipeline::getSuggestion;
Map ageCreditMap = statisticsPipelineList
.stream()
.collect(Collectors.groupingBy(y -> ageCredit.apply(y.getAge()), Collectors.averagingDouble(mapper)));多个数据求集合
private BiFunction accumulator = (x, y) -> new Integer[]{
x[0] + y.getAuth(), x[1] + y.getAntiFraud(), x[2] + y.getCreditRule(), x[3] + y.getModelReject(), x[4] + y.getSuggestion()
};
private BinaryOperator combiner = (x, y) -> new Integer[]{x[0] + y[0], x[1] + y[1], x[2] + y[2], x[3] + y[3], x[4] + y[4]};
Integer[] detail = approvePipelineList.stream().reduce(new Integer[]{0, 0, 0, 0, 0}, accumulator, combiner);多个数据求集合-多重合并
private BiFunction accumulator = (x, y) -> new Integer[]{
x[0] += y.getAuth(), x[1] += y.getAntiFraud(), x[2] += y.getCreditRule(), x[3] += y.getModelReject(), x[4] += y.getSuggestion()
};
BiFunction>, Integer[]> newAccumulator = (x, y) -> {
List pipelineList = y.getValue();
Integer[] data = pipelineList.stream().reduce(new Integer[]{0, 0, 0, 0, 0}, accumulator, combiner);
return new Integer[]{
x[0] += data[0], x[1] += data[1], x[2] += data[2], x[3] += data[3], x[4] += data[4]
};
};
Integer[] total = channelMap.entrySet().stream().reduce(new Integer[]{0, 0, 0, 0, 0}, newAccumulator, combiner);map最大多项和
Long hourC3 = hourMap.entrySet().stream().mapToLong(Map.Entry::getValue).sorted().limit(3).sum();