Skip to content

Commit 19f096b

Browse files
committed
java stream examples
java stream examples
1 parent bc62846 commit 19f096b

File tree

1 file changed

+87
-0
lines changed
  • java-stream/src/main/java/com/hmkcode

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.hmkcode;
2+
3+
import java.util.Arrays;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
import java.util.stream.Collectors;
7+
import java.util.stream.Stream;
8+
9+
public class App
10+
{
11+
public static void main( String[] args )
12+
{
13+
String[] arr = new String[]{"a", "b", "c", "d"};
14+
Stream<String> stream = Arrays.stream(arr);
15+
16+
stream = Stream.of("a", "b", "c", "d");
17+
18+
List<String> list = new LinkedList<String>();
19+
list.add("a");
20+
list.add("b");
21+
stream = list.stream();
22+
23+
// forEach()
24+
stream = Stream.of("a", "b", "c", "d");
25+
stream.forEach(e -> System.out.println(e));
26+
27+
// distinct() | count()
28+
stream = Stream.of("a", "b", "c", "d");
29+
System.out.println(stream.distinct().count());
30+
31+
// anyMatch()
32+
stream = Stream.of("a", "b", "c", "d");
33+
System.out.println(stream.anyMatch(e -> e.contains("a")));
34+
35+
// filter()
36+
stream = Stream.of("a", "b", "c", "d");
37+
stream.filter(e -> e.contains("b")).forEach(e -> System.out.println(e));
38+
39+
// map()
40+
stream = Stream.of("a", "b", "c", "d");
41+
stream.map(e -> e.toUpperCase()).forEach(e -> System.out.println(e));
42+
43+
// flatMap()
44+
stream = getBigList().stream().flatMap(lst -> lst.stream());
45+
stream.forEach(e -> System.out.println(e));
46+
47+
//[any|all|none]Match()
48+
System.out.println(Stream.of("a", "b", "c", "d").allMatch( e -> (e.length() == 1)));
49+
System.out.println(Stream.of("a", "b", "c", "d").noneMatch(e -> (e.length() == 2)));
50+
System.out.println(Stream.of("a", "b", "c", "d").anyMatch( e -> e.equals("a") ));
51+
52+
//reduce()
53+
stream = Stream.of("a", "b", "c", "d");
54+
System.out.println(stream.reduce("", (x,y) -> apply(x,y)));
55+
56+
//collect(Collectors)
57+
stream = Stream.of("a", "b", "c", "d");
58+
System.out.println(stream.collect(Collectors.toList()));
59+
60+
61+
}
62+
63+
private static String apply(String a, String b){
64+
System.out.println(a+"->"+b);
65+
return a+b;
66+
}
67+
68+
private static List<List<String>> getBigList(){
69+
70+
List<List<String>> bigList = new LinkedList<List<String>>();
71+
72+
List<String> list1 = new LinkedList<String>();
73+
list1.add("a");
74+
list1.add("b");
75+
76+
List<String> list2 = new LinkedList<String>();
77+
list2.add("c");
78+
list2.add("d");
79+
80+
bigList.add(list1);
81+
bigList.add(list2);
82+
83+
return bigList;
84+
}
85+
86+
87+
}

0 commit comments

Comments
 (0)