简体   繁体   English

Java使用流和Lambda表达式代替迭代器

[英]Java Using Stream and Lambda Expressions Instead of Iterator

I have an assignment for my Computer Science course and our instructor wants us to use Stream and Lambda expressions for an iterator. 我有一个计算机科学课程的作业,我们的老师希望我们为迭代器使用Stream和Lambda表达式。 I haven't seen the warning and I wrote the needed code according to my own taste and here it is: 我没有看到警告,而是根据自己的喜好编写了所需的代码,这里是:

static List<User> getUsers(String firstName){
    Iterator<User> it = users.iterator();
    ArrayList<User> tempList = new ArrayList<User>();
    while(it.hasNext()){
        User tempUser = it.next();
        if(tempUser.getFirstName().equals(firstName)){
            tempList.add(tempUser);
        }
    }
    return tempList;
}

How can I turn this into a Stream & Lambda code? 如何将其转换为Stream&Lambda代码? Thanks so much for your answers. 非常感谢您的回答。

Try this 尝试这个

List<User> tempUsers = users.stream()
    .filter(tempUser -> tempUser.getFirstName().equals(firstName))
    .collect(Collectors.toList());
//TODO do something useful with it

Your whole method can be reduce in one statement which don't use intermediate variable for the List : 您的整个方法可以简化为一个不使用中间变量作为List的语句:

static List<User> getUsers(String firstName){
   return users.stream()                                        //iterate
               .filter(u -> u.getFirstName().equals(firstName)) //keep good ones
               .collect(Collectors.toList());                   //collect them in List
}
  • u in the filter method is a local variable which will represent each element of users list, you can name it whatever you want u在filter方法中是一个局部变量,它将代表users列表的每个元素,您可以根据需要命名它
  • .toCollection(ArrayList::new) will assure you to have a ArrayList instead of toList() which can change later but no problem using it There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; .toCollection(ArrayList::new)将确保您拥有一个ArrayList而不是toList() ,该列表稍后可以更改,但使用它没有问题。 无法保证返回的List的类型,可变性,可序列 toList() 或线程安全性; if more control over the returned List is required, use toCollection(Supplier) from the doc 如果需要对返回的List进行更多控制,请使用 doc中的toCollection(Supplier)

You can create a stream from the users and then perform a filter operation to retain all users whos name equals firstName and then utilize Collectors.toCollection to accumulate the results into an ArrayList . 您可以从用户创建流,然后执行filter操作以保留名称等于firstName所有用户,然后利用Collectors.toCollection将结果累加到ArrayList

List<User> tempList = users.stream()
                           .filter(e -> e.getFirstName().equals(firstName))
                           .collect(Collectors.toCollection(ArrayList::new));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM