在JAVA中,涉及到对数组
、Collection
等集合类中的元素进行操作的时候,通常会通过循环的方式进行逐个处理,或者使用Stream的方式进行处理。
如:从给定句子中返回单词长度大于5的单词列表,按长度倒序输出,最多返回3个。
1.在JAVA7及之前的代码
public List<String> sortGetTop3LongWords(@NotNull String sentence) {
// 先切割句子,获取具体的单词信息
String[] words = sentence.split(" ");
List<String> wordList = new ArrayList<>();
// 循环判断单词的长度,先过滤出符合长度要求的单词
for (String word : words) {
if (word.length() > 5) {
wordList.add(word);
}
}
// 对符合条件的列表按照长度进行排序
wordList.sort((o1, o2) -> o2.length() - o1.length());
// 判断list结果长度,如果大于3则截取前三个数据的子list返回
if (wordList.size() > 3) {
wordList = wordList.subList(0, 3);
}
return wordList;
}
2.在JAVA8及之后的版本中,借助Stream流
public List<String> sortGetTop3LongWordsByStream(@NotNull String sentence) {
return Arrays.stream(sentence.split(" "))
.filter(word -> word.length() > 5)
.sorted((o1, o2) -> o2.length() - o1.length())
.limit(3)
.collect(Collectors.toList());
}
3.Stream流操作分为3种类型:
- 创建Stream
- Stream中间处理
- 终止Steam
每个Stream管道操作类型都包含若干API方法:
- 开始管道
主要负责新建一个Stream流,或者基于现有的数组、List、Set、Map等集合类型对象创建出新的Stream流。
- 中间管道
负责对Stream进行处理操作,并返回一个新的Stream对象,中间管道操作可以进行叠加。
- 终止管道
通过终止管道操作之后,Stream流将会结束,最后可能会执行某些逻辑处理,或者是按照要求返回某些执行后的结果数据。
4.Stream方法使用
4.1 map与flatMap
都是用于转换已有的元素为其它元素,区别点在于:
- map 必须是一对一的,即每个元素都只能转换为1个新的元素
- flatMap 可以是一对多的,即每个元素都可以转换为1个或者多个新的元素
如:有一个字符串ID列表,现在需要将其转为User对象列表
/**
* 演示map的用途:一对一转换
*/
public void stringToIntMap() {
List<String> ids = Arrays.asList("205", "105", "308", "469", "627", "193", "111");
// 使用流操作
List<User> results = ids.stream()
.map(id -> {
User user = new User();
user.setId(id);
return user;
})
.collect(Collectors.toList());
System.out.println(results);
}
结果:
[User{id='205'},
User{id='105'},
User{id='308'},
User{id='469'},
User{id='627'},
User{id='193'},
User{id='111'}]
每一个元素都被转换为对应新的元素,但是前后总元素个数是一致的
如:现有一个句子列表,需要将句子中每个单词都提取出来得到一个所有单词列表。这种情况用map就搞不定了,需要flatMap
上场了
public void stringToIntFlatmap() {
List<String> sentences = Arrays.asList("hello world","Wo Shi Zhang San");
// 使用流操作
List<String> results = sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(" ")))
.collect(Collectors.toList());
System.out.println(results);
}
结果:
[hello, world, Wo, Shi, Zhang, San]
结果列表中元素个数是比原始列表元素个数要多的:
flatMap
操作的时候其实是先每个元素处理并返回一个新的Stream,然后将多个Stream展开合并为了一个完整的新的Stream,如下:
4.2 peek和foreach方法
都可以用于对元素进行遍历然后逐个的进行处理。
peek属于中间方法,而foreach属于终止方法。这也就意味着peek只能作为管道中途的一个处理步骤,而没法直接执行得到结果,其后面必须还要有其它终止操作的时候才会被执行;而foreach作为无返回值的终止方法,则可以直接执行相关操作。
4.3 filter、sorted、distinct、limit
这几个都是常用的Stream的中间操作方法,具体的方法的含义在上面的表格里面有说明。具体使用的时候,可以根据需要选择一个或者多个进行组合使用,或者同时使用多个相同方法的组合:
public void testGetTargetUsers() {
List<String> ids = Arrays.asList("205","10","308","49","627","193","111", "193");
// 使用流操作
List<Dept> results = ids.stream()
.filter(s -> s.length() > 2)
.distinct()
.map(Integer::valueOf)
.sorted(Comparator.comparingInt(o -> o))
.limit(3)
.map(id -> new Dept(id))
.collect(Collectors.toList());
System.out.println(results);
}
1.使用filter过滤掉不符合条件的数据
2.通过distinct对存量元素进行去重操作
3.通过map操作将字符串转成整数类型
4.借助sorted指定按照数字大小正序排列
5.使用limit截取排在前3位的元素
6.又一次使用map将id转为Dept对象类型
7.使用collect终止操作将最终处理后的数据收集到list中
结果:
[Dept{id=111}, Dept{id=193}, Dept{id=205}]
4.4 简单结果终止方法
终止方法里面像count
、max
、min
、findAny
、findFirst
、anyMatch
、allMatch
、nonneMatch
等方法,均属于这里说的简单结果终止方法。所谓简单,指的是其结果形式是数字、布尔值或者Optional对象值等。
public void testSimpleStopOptions() {
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
// 统计stream操作后剩余的元素个数
System.out.println(ids.stream().filter(s -> s.length() > 2).count());
// 判断是否有元素值等于205
System.out.println(ids.stream().filter(s -> s.length() > 2).anyMatch("205"::equals));
// findFirst操作
ids.stream().filter(s -> s.length() > 2)
.findFirst()
.ifPresent(s -> System.out.println("findFirst:" + s));
}
结果
6
true
findFirst:205
一旦一个Stream被执行了终止操作之后,后续便不可以再读这个流执行其他的操作了
4.5 结果收集终止方法
因为Stream主要用于对集合数据的处理场景,更多的场景是获取一个集合类的结果对象,比如List、Set或者HashMap等。
这里就需要collect
方法了,它可以支持生成如下类型的结果数据:
- 一个
集合类
,比如List、Set或者HashMap等 - StringBuilder对象,支持将多个
字符串进行拼接
处理并输出拼接后结果 - 一个可以记录个数或者计算总和的对象(
数据批量运算统计
)
4.5.1 生成集合
public void testCollectStopOptions() {
List<Dept> ids = Arrays.asList(new Dept(17), new Dept(22), new Dept(23));
// collect成list
List<Dept> collectList = ids.stream().filter(dept -> dept.getId() > 20)
.collect(Collectors.toList());
System.out.println("collectList:" + collectList);
// collect成Set
Set<Dept> collectSet = ids.stream().filter(dept -> dept.getId() > 20)
.collect(Collectors.toSet());
System.out.println("collectSet:" + collectSet);
// collect成HashMap,key为id,value为Dept对象
Map<Integer, Dept> collectMap = ids.stream().filter(dept -> dept.getId() > 20)
.collect(Collectors.toMap(Dept::getId, dept -> dept));
System.out.println("collectMap:" + collectMap);
}
结果:
collectList:[Dept{id=22}, Dept{id=23}]
collectSet:[Dept{id=23}, Dept{id=22}]
collectMap:{22=Dept{id=22}, 23=Dept{id=23}}
4.5.2 生成拼接字符串
将一个List或者数组中的值拼接到一个字符串里并以逗号分隔开;
如果通过for
循环和StringBuilder
去循环拼接,还得考虑下最后一个逗号如何处理的问题,很繁琐:
public void testForJoinStrings() {
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
StringBuilder builder = new StringBuilder();
for (String id : ids) {
builder.append(id).append(',');
}
// 去掉末尾多拼接的逗号
builder.deleteCharAt(builder.length() - 1);
System.out.println("拼接后:" + builder.toString());
}
Stream使用collect
可以轻而易举的实现:
public void testCollectJoinStrings() {
List<String> ids = Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
String joinResult = ids.stream().collect(Collectors.joining(","));
System.out.println("拼接后:" + joinResult);
}
4.5.3 数据批量数学运算
使用collect生成数字数据的总和信息
public void testNumberCalculate() {
List<Integer> ids = Arrays.asList(10, 20, 30, 40, 50);
// 计算平均值
Double average = ids.stream().collect(Collectors.averagingInt(value -> value));
System.out.println("平均值:" + average);
// 数据统计信息
IntSummaryStatistics summary = ids.stream().collect(Collectors.summarizingInt(value -> value));
System.out.println("数据统计信息: " + summary);
}
结果:
平均值:30.0
总和: IntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50}
5.并行Stream
使用并行流,可以有效利用计算机的多CPU硬件,提升逻辑的执行速度。并行流通过将一整个stream划分为多个片段
,然后对各个分片流并行执行处理逻辑,最后将各个分片流的执行结果汇总为一个整体流。
并行流类似于多线程在并行处理,所以与多线程场景相关的一些问题同样会存在,比如死锁等问题,所以在并行流终止执行的函数逻辑,必须要保证线程安全。