Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

Java8 Lambda and Stream

好用的酷東西。

函式寫法 (Parameters) -> {Statments}

Public int add(int a, int b){return a+b};
改成
(a,b) ->a+b;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
statement lambda
()-> {chimera.Sound();}

expression lambda
()-> chimera.Sound()


// 一般寫法
public class RunnableImpl implements Runnable{
public void run() {
System.out.print("Run method");
}
}

// usage
Runnable runnableObject = new RunnableImpl();

// Anonymous class
Runnable r = new Runnable() {
@Override
public void run() {
System.out.print("Run method");
}
};

// 改成lambda

Runnable r = ()->{ System.out.print("Run method");}

方法引用 Class name :: method

Function<String, Integer> StI = (String s) -> Integer.parseInt(s);
等同
Function<String, Integer> StI = Integer::parseInt;

更多範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Demo {
public static void main(String[] args){

String[] array = {"a","b","c"};
List<String> list = Arrays.asList(array);

// Java7
for(String s:list){
System.out.println(s);
}

// Java8
list.forEach(System.out::println);

public static void print(String content){
System.out.println(content);
}

// Java8
list.forEach(Demo :: print); // with static method
list.forEach(super :: print); // with super method
list.forEach(new Demo() :: print); // with instance method

List<String> mylist = Arrays.asList("Hello","World");
mylist.stream()
.map(String::toUpperCase)
.forEach(System.out::println);

}}

構造器 Class name :: new

Supplier supplier = ()->new User();
等同
Supplier supplier = User :: new;

Stream

1
2
3
4
5
6
7
8
9
// create Stream
Stream<String> language = Stream.of("Java","Python", "Java");
List<String> listResult = language.collect(Collectors.toList());
result.forEach(System.out::println);

// use stream()
List<String> languagelist = Arrays.asList("Java","Python", "Java");
List<String> listResult = languagelist.stream().collect(Collectors.toList()); // Collectors.toSet()... set不重複 Collectors.joining(","); 加入, 組合
listResult.forEach(System.out::println);

Serializable

標示類可以進行序列化的介面

Filter

1
2
3
4
5
List<String> name = Arrays.asList("Eric", "Shvara", "Lunski");
List<String> output = name.filter(value -> value.equals("Lunski"));

// filter in stream
List<String> dataList = dataList.stream().filter(d -> d.length() > 5);

Map

1
2
3
4
5
List<String> person = Arrays.asList("Eric", "Shvara", "Lunski");
List<String> names = person.map(o->o.getName());

// map in stream, transfer person list to stream, set and store in codes set
Set<String> codes = person.stream().map(o -> "Code: "+o.getCode()).collect(Collectiors.toSet()));

Stream list to map

Others

Java 8 Lambda

distinct, sorted, limit, skip, reduce, min, max, match


如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels