Stream流 操作List<T>集合

前言:java8提供了很多操作集合的,以下是写的一些简单的案例。希望能有用 (* ̄︶ ̄)。

更多Stream操作可参考: www.ibm.com/developerwo…

/**
 * @author DHing
 */
public class Streams { 
   public static void main(String[] args) {
        
        List<User> user = new ArrayList<>();
        User u = new User();
        u.setAge(1);
        u.setName("hello");
        User u3 = new User();
        u3.setAge(2);
        u3.setName("hello2");
        user.add(u);
        user.add(u3);
        
        user.forEach(u1 -> {
            System.out.println(u1.getAge() + " " + u1.getName());
        });
        
    //输出指定类型
    List<Integer> collect = user.stream().map(a -> Integer.getInteger(a.getName())).collect(Collectors.toList());

        //匹配名字为hello的对象集合
          List<User> collect = user.stream().filter(a -> "hello".equals(a.getName())) .collect(Collectors.toList()); //没有去重
          List<User> collect3 = user.stream().filter(a -> "hello".equals(a.getName())).distinct().collect(Collectors.toList()); //去重
        //limit
         List<User> collect2 = user.stream().limit(2).collect(Collectors.toList());
         //count
         user.stream().filter(a -> a.getAge() > 10).count();
        System.out.println(collect2);
        //求年龄总和
        user.stream().map(a -> a.getAge()).reduce(0, Integer::sum);
        //等同上面 求和
         user.stream().mapToInt(User :: getAge).sum();
         //平均
         user.stream().mapToInt(User :: getAge).average();
         //最小
         user.stream().mapToInt(User :: getAge).min();
         //最大
         user.stream().mapToInt(User :: getAge).max();
         //年龄 乘 10
         user.stream().mapToDouble(w -> w.getAge() * 10).sum();
         //排序
         user.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(Collectors.toList());
         //分组
         user.stream().collect(Collectors.groupingBy(User::getAge));
         //匹配
         boolean flag = user.stream().allMatch(a -> a.getAge() > 10);
         boolean flag1 = user.stream().noneMatch(a -> a.getAge() > 10);
         //获取集合对象值
         String name = user.stream().filter(u5 -> u5.getAge() == 1).map(User:: getName).findFirst().get();
         
         //取指定字段为一个新的集合
         user.stream().map(us -> {
             User u1 = new User();
             u1.setAge(us.getAge() + 10);
             return u1;
         }).collect(Collectors.toList());
         //同理转为一个map集合
         user.stream().map(us -> {
             Map u1 = new HashMap();
             u1.put("age", us.getAge());
             u1.put("name", us.getName());
             return u1;
         }).collect(Collectors.toList());

        //List<User> ——> Map<Integer,String>
        Map<Integer, String> map = user
            .stream()
            .collect
                (Collectors.toMap(User::getAge, User::getName));
        System.out.println(map);//{1=hello, 2=hello2}
      //List<User> ——-> Map<Integer, User>
        Map<Integer, User> map1 = user
            .stream()
            .collect
                (Collectors.toMap(User::getAge, Function.identity()));
         map1.entrySet().forEach(System.out::println); // 1=Streams$User@682a0b20 ,2=Streams$User@4dd8dc3

       // List<User> ————> Map<String, List<User>>
        Map<String, List<User>> groupedByName = user
            .stream()
            .collect
                (Collectors.groupingBy(User::getName));
        System.out.println(groupedByName); //{hello2=[Streams$User@4dd8dc3], hello=[Streams$User@682a0b20]}
         
    }
 static class User{
        private String name;
        private Integer age;
        
        public String getName() {
            return name;
        }
      
        public void setName(String name) {
            this.name = name;
        }
        
        public Integer getAge() {
            return age;
        }
         
        public void setAge(Integer age) {
            this.age = age;
        }
    }
}复制代码

GroupBy可参考: blog.csdn.net/u011663149/…

Map.merge() 可参考: blog.csdn.net/u011663149/…

Collectors 可参考:blog.csdn.net/u011663149/…



转载于:https://juejin.im/post/5cf643c46fb9a07efa090579

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用stream的filter方法来过滤List<Record>的元素,例如: List<Record> records = new ArrayList<>(); // 添加记录到列表中 Stream<Record> filteredRecords = records.stream().filter(record -> record.getStatus().equals("active")); // 过滤出状态为"active"的记录 List<Record> activeRecords = filteredRecords.collect(Collectors.toList()); ### 回答2: 在Java中,可以使用Stream来过滤List<Record>的元素。Stream提供了一种简洁、灵活和高效的处理集合数据的方式。 首先,我们需要将List<Record>转换成一个Stream。可以使用Liststream()方法来获取一个Stream对象,该对象代表了List中的元素。 接下来,可以使用filter()方法来对元素进行过滤。filter()方法需要一个Predicate<T>参数,用于指定过滤条件。在这个参数中,我们可以定义一个Lambda表达式来指定过滤条件。 Lambda表达式的参数是中的每个元素,需要根据元素的某些属性或条件来判断是否保留该元素。如果条件满足,则保留该元素;否则,过滤掉该元素。 最后,可以使用collect()方法将过滤后的元素收集到一个新的List中。collect()方法需要一个Collector参数,我们可以使用Collectors.toList()方法来创建一个收集器,用于将元素收集到新的List中。 下面是一个示例代码,演示如何使用Stream过滤List<Record>的元素: ``` import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Record> records = // 获取记录的方法,省略 List<Record> filteredRecords = records.stream() .filter(record -> record.getProperty() > 10) // 过滤条件,保留属性大于10的记录 .collect(Collectors.toList()); // 打印过滤后的记录 filteredRecords.forEach(System.out::println); } } ``` 在以上示例中,假设List<Record>中的Record类有一个getProperty()方法,用于获取记录的某个属性值。示例代码使用filter()方法过滤了属性大于10的记录,并将过滤后的记录收集到了filteredRecords列表中。最后,我们通过forEach()方法来遍历并打印过滤后的记录。 通过以上方法,可以很方便地使用Stream来过滤List<Record>的元素。 ### 回答3: 在Java中,可以使用Stream进行过滤List<Record>的元素。Stream是一种用于处理集合数据的标准化操作的抽象,可以用于对集合进行筛选、排序、映射等操作。 首先,我们需要将List<Record>转换Stream。可以使用Liststream()方法来获取一个Stream对象,例如: Stream<Record> recordStream = recordList.stream(); 然后,我们可以使用filter()方法对中的元素进行过滤操作。filter()方法接受一个Predicate函数式接口作为参数,该接口用于判断元素是否满足某个条件。例如,我们可以过滤出满足某个条件的Record对象,代码如下: recordStream = recordStream.filter(record -> record.getField().equals("某个条件")); 接下来,我们可以继续对过滤后的进行其他操作,例如对结果进行排序、映射等等。最后,我们可以使用collect()方法将转换List<Record>类型的对象,代码如下: List<Record> filteredList = recordStream.collect(Collectors.toList()); 通过以上的Stream操作,我们可以简洁地过滤List<Record>的元素,并得到满足条件的Record对象的列表。注意,Stream操作是惰性求值的,只有在执行终止操作(如collect()方法)时才会进行计算和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值