jdk8新特性lambd表达式和stream

stream位于java.util.stream包,是一个接口

@FunctionalInterface
interface IConvert<F, T>
接口 IConvert,传参为类型 F,返回类型 T。
注解@FunctionalInterface保证了接口有且仅有一个抽象方法,所以JDK能准确地匹配到相应方法。

方法引用的标准形式是:类名::方法名
有以下四种形式的方法引用:
引用静态方法 ContainingClass::staticMethodName
引用某个对象的实例方法 containingObject::instanceMethodName
引用某个类型的任意对象的实例方法 ContainingType::methodName
引用构造方法 ClassName::new

接口方法有:
of(T… values)
of(T t)
collect(Collector<? super T, A, R> collector);
A[] toArray(IntFunction<A[]> generator);
Stream filter(Predicate<? super T> predicate)
T reduce(T identity, BinaryOperator accumulator);

1.构建一个stream
Stream value = Stream.of(“a”, “b”, “c”);
2.输出stream
value.forEach(System.out::println);
结果
a
b
c

3.数组转换成stream
String[] a = new String[] {“a”, “b”, “c”};
Stream value = Stream.of(a);

3、List转成stream
List list = new ArrayList<>();
list.add(“zhangsan”);
list.add(“lisi”);
list.add(“wangwu”);
Stream stream = list.stream();
stream.forEach(System.out::println);

结果
zhangsan
lisi
wangwu

4.Map转成stream
HashMap<String, String> map = new HashMap<>();
map.put(“name”, “张三”);
map.put(“sex”, “男”);
map.put(“age”, “22”);
map.put(“address”, “北京市昌平区”);
Stream<Entry<String, String>> stream = map.entrySet().stream();
stream.forEach(System.out::println);

结果
address=北京市昌平区
sex=男
name=张三
age=22

5、stream转换成数组
Stream stream = Stream.of(“a”,“b”,“c”);
String[] a = stream.toArray(String[]::new);

6、stream转换成List
Stream stream = Stream.of(“a”,“b”,“c”);
List list = stream.collect(Collectors.toList());
list.forEach(System.out::print);

结果
abc

7、stream转String
Stream stream = Stream.of(“a”,“b”,“c”);
String str = stream.collect(Collectors.joining()).toString();
System.out.println(str);

结果
abc

8、stream进行过滤
List list = new ArrayList<>();
list.add(“zhangsan”);
list.add(“lisi”);
list.add(“wangwu”);
Stream stream = list.stream();
String str = stream.filter(l -> l.equals(“lisi”)).collect(Collectors.joining()).toString();
System.out.println(str);

结果
lisi

9、peek操作
Stream.of(“one”, “two”, “three”, “four”)
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList());

结果
Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR

10、reduce操作
double minValue = Stream.of(-1.5,1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
System.out.println(minValue);

结果
-3.0

int minValue = Stream.of(2, 3, 4, -2).reduce(0, Integer::sum);
System.out.println(minValue);

结果
7

猜你喜欢

转载自blog.csdn.net/zhanglinlove/article/details/83865748
今日推荐