前面介绍了lambda还有stream,现在给一些例子加强lambda与stream的理解。
例子1
小写字母转大写字母
List<String> output = wordList.
stream().
map(String::toUpperCase).
collect(Collectors.toList());
过滤掉字符串长度为单数的字符串
List<String> output = wordList.
stream().
filter(w -> (w.length() & 1) == 0).
collect(Collectors.toList());
累计输入流里有多少行
long count = bufferedReader.
lines().
count();
例子4
求出输入流中长度最长的字符串长度
int longest = bufferedReader.
lines().
mapToInt(String::length).
max(). //求出输入流中长度最长的字符串长度
getAsInt();
注意这里的mapToInt() 与 max() 都是中间方法返回的类型分别是IntStream 与 OptionalInt,所以需要 getAsInt() 来做终点方法。
例子5
读取BufferedReader的数据存入List中
List<String> output = bufferedReader.
lines().
flatMap(line -> Stream.of(line)).
filter(word -> word.length() > 0).
collect(Collectors.toList());
例子6
读取数据同时对数据做其他处理
List<String> output = bufferedReader.
lines().
flatMap(line -> Stream.of(line.split("/r/n"))).
filter(word -> word.length() > 0).
map(String::toLowerCase).
distinct().
sorted().
collect(Collectors.toList());
这里的处理有 split() 对字符串就行分割, distinct() 去重, sorted() 排序。