stream
使用stream可以遍历一个collection(Array也可以),使用map(对每个元素执行操作)、filter(过滤)等操作产生一个新的collection。
流的操作:
- Intermediate:
mapfilterdistinctsortedpeeklimitskipparallelsequentialunordered - Terminal:
forEachforEachOrderedtoArrayreducecollectminmaxcountanyMatchallMatchnoneMatchfindFirstfindAnyiterator - Short-circuiting:
anyMatchallMatchnonMatchfindFirstfindAnylimit
*** => stream1
2
3
4
5
6
7
8
9// 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();
stream => ***1
2
3
4
5
6
7
8
9// 1. Array
String[] strArray1 = stream.toArray(String[]::new);
// 2. Collection
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
Set set1 = stream.collect(Collectors.toSet());
Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
// 3. String
String str = stream.collect(Collectors.joining()).toString();
map
1 | //转换大写,wordList为单词集合List<String>类型 |
filter
1 | //留下偶数,经过条件“被 2 整除”的 filter,剩下的数字为 {2, 4, 6}。 |
forEach
1 | //打印所有男性姓名,roster为person集合类型为List<Pserson> |
forEach是Terminal操作,会消费掉元素,与其功能对应的Intermediate操作为peek
reduce
reduce用于把Stream元素组合起来,它提供一个起始值,依照一个运算函数(二元),将其分别与每个元素进行运算。如果不设置起始值,返回为Optional
1 | // 字符串连接,concat = "ABCD" |
sorted
1 | List<Person> persons = new ArrayList(); |
Match
- allMatch: 全部符合返回true
- anyMatch: 有一个符合就返回true
- noneMatch: 全部不符合返回true
1 | //Match使用示例 |