java list stream use

1. Traverse/match (foreach/find/match)

List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);  
// 遍历输出符合条件的元素  
list.stream().filter(x -> x > 6).forEach(System.out::println);  
// 匹配第一个  
Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();  
// 匹配任意(适用于并行流)  
Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();  
// 是否包含符合特定条件的元素  
boolean anyMatch = list.stream().anyMatch(x -> x < 6);  

 2. Filter

// 筛选出Integer集合中大于7的元素
List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9);  
Stream<Integer> stream = list.stream();  
stream.filter(x -> x > 7).forEach(System.out::println);  
// 筛选员工中工资高于8000的人,并形成新的集合
List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName).collect(Collectors.toList());  

3. Aggregation (max/min/count)

// 获取String集合中最长的元素 
List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");  
Optional<String> max = list.stream().max(Comparator.comparing(String::length));

// 获取Integer集合中的最大值
List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6);  
   // 自然排序  
   Optional<Integer> max = list.stream().max(Integer::compareTo);  
   // 自定义排序  
   Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() {  
     @Override  
     public int compare(Integer o1, Integer o2) {  
       return o1.compareTo(o2);  
     }  
  });

// 获取员工工资最高的人
Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));  
System.out.println("员工工资最大值:" + max.get().getSalary());

//计算Integer集合中大于6的元素的个数
List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9);  
long count = list.stream().filter(x -> x > 6).count();

4. Mapping (map/flatMap)

// 英文字符串数组的元素全部改为大写
  String[] strArr = { "abcd", "bcdd", "defde", "fTr" };  
  List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());  

// 整数数组每个元素+3
  List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);  
  List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList());

// 将员工的薪资全部增加1000
  // 返回新实体  
  List<User> list1 = listUser.stream().map(item -> {  
   User user = new User(item.getName(), 0, 0, null, null);  
   user.setSalary(item.getSalary() + 10000);  
   return user;  
  }).collect(Collectors.toList()); 
  
  // 返回旧实体
  List<User> list2= listUser.stream().map(item -> {  
   item.setSalary(item.getSalary() + 10000);  
   return item;  
  }).collect(Collectors.toList());  

// 将两个字符数组合并成一个新的字符数组
 List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");  
 List<String> listNew = list.stream().flatMap(item -> {  
   // 将每个元素转换成一个stream  
   String[] split = item.split(",");  
   Stream<String> spilitStr = Arrays.stream(split);  
   return spilitStr;  
 }).collect(Collectors.toList());  

 //方式一
 Map<String, String> stringMap = listUser.stream().collect(Collectors.toMap(v -> String.valueOf(v.getId()), v -> v.getName()));
 //方式二
 Map<Long, String> stringMap2 = listUser.stream().collect(Collectors.toMap(User::getId, Stu::getName));

 Map<Long,User> orderCarStoreInfoMap =  listUser.stream().collect(
                Collectors.toMap(User::getId, item1 -> item1 ));
 
 //转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。
 // 转成map的时候,最好使用下面的方式:
 Map<Long, User> maps = listUser.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
 
 Map<Long, String> maps1 = listUser.stream().collect(Collectors.toMap(User::getId, Stu::getName, (key1, key2) -> key2));
 
 //List 以ID分组 Map
 Map<Long, List<User>> groupBy = listUser.stream().collect(Collectors.groupingBy(User::getId));

5. Reduce

// 求Integer集合的元素之和、乘积和最大值  
List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);  
  // 求和方式1  
  Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);  
  // 求和方式2  
  Optional<Integer> sum2 = list.stream().reduce(Integer::sum);  
  // 求和方式3  
  Integer sum3 = list.stream().reduce(0, Integer::sum);  
    
  // 求乘积  
  Optional<Integer> product = list.stream().reduce((x, y) -> x * y);  
  
  // 求最大值方式1  
  Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);  
  // 求最大值写法2  
  Integer max2 = list.stream().reduce(1, Integer::max);  

// 求所有员工的工资之和和最高工资
  // 求工资之和方式1:  
  Optional<Integer> sumSalary = userList.stream().map(User::getSalary).reduce(Integer::sum);  
  // 求工资之和方式2:  
  Integer sumSalary2 = userList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),  
    (sum1, sum2) -> sum1 + sum2);  
  // 求工资之和方式3:  
  Integer sumSalary3 = userList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);  
  
  // 求最高工资方式1:  
  Integer maxSalary = userList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),  
    Integer::max);  
  // 求最高工资方式2:  
  Integer maxSalary2 = userList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),  
    (max1, max2) -> max1 > max2 ? max1 : max2);

6. collect

// 归集(toList/toSet/toMap)
List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);  
  List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());  
  Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());    
  Map<?, Person> map = userList.stream().filter(p -> p.getSalary() > 8000)  
    .collect(Collectors.toMap(User::getName, p -> p));  

//统计(count/averaging)

// 求总数  
  Long count = userList.stream().collect(Collectors.counting());  
  // 求平均工资  
  Double average = userList.stream().collect(Collectors.averagingDouble(User::getSalary));  
  // 求最高工资  
  Optional<Integer> max = userList.stream().map(User::getSalary).collect(Collectors.maxBy(Integer::compare));  
  // 求工资之和  
  Integer sum = userList.stream().collect(Collectors.summingInt(User::getSalary));  
  // 一次性统计所有信息  
  DoubleSummaryStatistics collect = userList.stream().collect(Collectors.summarizingDouble(User::getSalary));  
  

// 分组(partitioningBy/groupingBy)

// 将员工按薪资是否高于10000分组  
        Map<Boolean, List<User>> part = userList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 10000    ));  
        // 将员工按性别分组  
        Map<String, List<User>> group = userList.stream().collect(Collectors.groupingBy(User::getSex));  
        // 将员工先按性别分组,再按地区分组  
        Map<String, Map<String, List<User>>> group2 = userList.stream().collect(Collectors.groupingBy(User::getSex, Collectors.groupingBy(User::getArea)));  
   

//接合(joining)
String names = userList.stream().map(p ->p.getName()).collect(Collectors.joining(","));

List<String> list = Arrays.asList("A", "B", "C");  
String string = list.stream().collect(Collectors.joining("-"));  

//归约(reducing) 
  Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));   
  
  Optional<Integer> sum2 = userList.stream().map(User::getSalary).reduce(Integer::sum);

7. Sorted

// 按工资增序排序  
  List<String> newList = userList.stream().sorted(Comparator.comparing(User::getSalary)).map(User::getName)  
    .collect(Collectors.toList());  
  // 按工资倒序排序  
  List<String> newList2 = userList.stream().sorted(Comparator.comparing(User::getSalary).reversed())  
    .map(User::getName).collect(Collectors.toList());  
  // 先按工资再按年龄自然排序(从小到大)  
  List<String> newList3 = userList.stream().sorted(Comparator.comparing(User::getSalary).reversed())  
    .map(User::getName).collect(Collectors.toList());  
  // 先按工资再按年龄自定义排序(从大到小)  
  List<String> newList4 = userList.stream().sorted((p1, p2) -> {  
   if (p1.getSalary() == p2.getSalary()) {  
    return p2.getAge() - p1.getAge();  
   } else {  
    return p2.getSalary() - p1.getSalary();  
   }  
  }).map(User::getName).collect(Collectors.toList());

8. Extraction/combination

Stream<String> stream1 = Stream.of(arr1);  
  Stream<String> stream2 = Stream.of(arr2);  
  // concat:合并两个流 distinct:去重  
  List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());  
  // limit:限制从流中获得前n个数据  
  List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());  
  // skip:跳过前n个数据  
  List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());  
  

1. Implement simple deduplication of List object collection (distinct())​

List<User> list = list.stream().distinct().collect(Collectors.toList());

 2. Implement deduplication of List collections based on attributes (name)

list = list.stream().filter(o -> o.getName() != null).collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName()))),ArrayList<Aoo>::new));

3. Implement simple filtering of List object collections (filtering objects that are null)

List<User> list = list.stream().filter(item -> item != null).collect(Collectors.toList());

4. Implement the List collection to obtain a certain attribute in the List object collection.

List<String> collect = apples.stream().map(User::getName).collect(Collectors.toList());

5. Group the List object collection according to a certain attribute of the object

Map<String, List<User>> userMap = list.stream().collect(Collectors.groupingBy(User :: getName));

6. Implement statistics of sum, maximum, minimum and average in List object collection

Long sum = list.stream().mapToLong(User::getAge).sum(); //和
Double max = list.stream().mapToDouble(User::getAge).max(); //最大
Integer = list.stream().mapToInt(User::getAge).min(); //最小
OptionalDouble average = list.stream().mapToDouble(User::getAge).average(); //平均值

7. Implement paging of List object collections

List<User> resultList = list.stream().skip(pageSize * (currentPage - 1)).limit(pageSize).collect(Collectors.toList());

Guess you like

Origin blog.csdn.net/piaomiao_/article/details/130271419