stream常用操作

Java Stream对象转换为Map

方法1:通过收集器(Collector)使用toMap()方法

Map<KeyType, ValueType> map = stream.collect(Collectors.toMap(obj -> obj.getFieldKey(), obj -> obj.getFieldValue()));

方法2:结合Collectors的toMap()方法和Function.identity(),使用对象自身作为key

Map<Object, ObjectType> map = stream.collect(Collectors.toMap(ObjectType::getFieldKey, Function.identity()));

方法3:如果存在重复的key,可以使用BinaryOperator来指定如何处理冲突的值

Map<KeyType, ValueType> map = stream.collect(Collectors.toMap(ObjectType::getFieldKey, ObjectType::getFieldValue, (value1, value2) -> value1));

方法4:使用Collectors的toMap()方法和Collectors.groupingBy()方法结合,将stream按照某个属性分组后转换为Map

Map<GroupKeyType, Map<KeyType, ValueType>> map = stream.collect(Collectors.groupingBy(ObjectType::getGroupKey, Collectors.toMap(ObjectType::getFieldKey, ObjectType::getFieldValue)));

方法5:使用Collectors的toMap()方法和Collectors.groupingBy()方法结合,将stream按照某个属性分组并汇总为List后转换为Map

Map<GroupKeyType, List<ObjectType>> map = stream.collect(Collectors.groupingBy(ObjectType::getGroupKey, Collectors.toList()));

map 方法用于映射每个元素到对应的结果

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter 方法用于通过设置的条件过滤出元素

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.stream().filter(string -> string.isEmpty()).count();

limit 方法用于获取指定数量的流

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

sorted 方法用于对流进行排序

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

parallelStream 是流并行处理程序的代替方法

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

  

posted @ 2024-12-02 13:47  a快乐码农  阅读(1)  评论(0编辑  收藏  举报