TrkDgnr
TrkDgnr

Reputation: 139

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. 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? Thanks so much for your answers.

Upvotes: 2

Views: 163

Answers (3)

azro
azro

Reputation: 54148

Your whole method can be reduce in one statement which don't use intermediate variable for the 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
  • .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; if more control over the returned List is required, use toCollection(Supplier) from the doc

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56393

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.

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

Upvotes: 1

CodeMatrix
CodeMatrix

Reputation: 2154

Try this

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

Upvotes: 1

Related Questions