1. 程式人生 > >jdk8新特性lambd表示式和stream

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