简单数据类型int,跟Integer在lambda中的使用还不一样,有区别
code:
package com.qhong.lambda.testDemo; import java.util.Arrays;
import java.util.Comparator;
import java.util.List; /**
* Created by qhong on 2018/5/23 9:30
**/
public class baseDemo { public static void main(String[] args) {
//int
int[] arr= {,,,,,,,,};
List<Integer> list= Arrays.asList(,,,,,,,,);
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.stream(arr).max().getAsInt());
System.out.println(list.stream().mapToInt(x->Integer.parseInt(x.toString())).max().getAsInt());
System.out.println(list.stream().mapToInt(x->Integer.valueOf(x.toString()).intValue()).min().getAsInt());
System.out.println(list.stream().max(Comparator.comparing(x->x)).get());
System.out.println(list.stream().max(Comparator.comparing(Integer::intValue)).get());
System.out.println("==============Integer=====================");
//Integer
Integer[] arr2= {,,,,,,,,};
System.out.println(Arrays.stream(arr2).mapToInt(x->Integer.parseInt(x.toString())).max().getAsInt());
}
}
boxed:
public class boxedTest { public static void main(String[] args) {
List<String> strings = Stream.of("how", "to", "do", "in", "java")
.collect(Collectors.toList());
System.out.println(strings);
List<Integer> ints= IntStream.of(,,,,).boxed()
.collect(Collectors.toList());
System.out.println(ints);
testPersonIds();
} private static void testPersonIds(){
List<Integer> list= getPersonList().stream()
.map(x->x.getIds().split(","))
.flatMap(x->Arrays.stream(x))
.mapToInt(x->Integer.parseInt(x))
.boxed()
.distinct()
.collect(Collectors.toList());
System.out.println(JSON.toJSONString(list));
} private static List<Person> getPersonList(){
return Arrays.asList(new Person[]{
new Person("hongda","1,2,3,4,5"),
new Person("hongdada","3,4,6,7,8"),
new Person("hongda3","8,9,10")
});
} @Data
@NoArgsConstructor
@AllArgsConstructor
static class Person{
private String name; private String ids;
}
}
mapToInt以后会转换成IntStream
使用boxed,会转换成Stream<Integer>
跟下面的方法进行对比:
private static void testPersonIds(){
Stream<Person> personStream=getPersonList().stream();
Stream<String[]> arrayStream= personStream.map(x->x.getIds().split(","));
Stream<String> stringStream=arrayStream.flatMap(x->Arrays.stream(x));
IntStream intStream=stringStream.mapToInt(x->Integer.parseInt(x));
Stream<Integer> integerStream=intStream.boxed();
Stream<Integer> integerStream1=integerStream.distinct();
List<Integer> list=integerStream1.collect(Collectors.toList());
System.out.println(JSON.toJSONString(list));
}
结果是一样的,这样可以很明显的看出类型的变化。
当然也可以把mapToInt,boxed这两个操作合并成一个map,这里举例使用
Stream<Integer> integerStream=stringStream.map(x->Integer.parseInt(x));
参考:
https://howtodoinjava.com/java-8/java8-boxed-intstream/
https://www.cnblogs.com/andywithu/p/7404101.html