2

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.

4
  • If he wants you to write lambdas, then he should have explained how to write the code in general. What have you tried so far? Commented Mar 25, 2018 at 13:27
  • She had added some tutorial files and oracle doc links for both Stream and Lambda expressions to the assignment pdf but we have never seen them before in class so I read the files but I didn't understand the syntax throughly so I decided to post a question here. However Aominè and azro explained very clearly, thanks so much again. Commented Mar 25, 2018 at 13:53
  • the syntax is simple: you write version of your code as if it was anonymous class, then gradually remove the extra code so that only "essential" parts remain. Commented Mar 25, 2018 at 14:56
  • Please accept an answer if one satisfies you and deals with your question Commented Mar 25, 2018 at 15:27

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer ! While using lambda expressions for the filter method, don't I need to declare what u is? And if I write .toList instead of .toCollection(ArrayList::new) like in the answer below, does it create an unspecified List, and if it does would it be a problem?
@TrkDgnr in addition to azro's answer. if you care about the type of the list returned and whether it's a mutable or immutable list etc then go for .toCollection(ArrayList::new). however, if that doesn't concern you then use .toList(). it's as simple as that.
@TrkDgnr as for don't I need to declare what u is?, you can like this .filter((User u) -> u.getFirstName().equals(firstName)) , but since the compiler can infer the type, you don't need to. whether you should explicitly specify the type or not is a matter of preference, thus go with whatever approach you want.
1

Try this

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

Comments

1

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));

2 Comments

Thank you for the quick response! Inside the filter method can I use more than one condition: .filter(e -> e.condition1() && e.condition2()) ?
@TrkDgnr sure you can. you can use as many conditions separated by a logical or or logical and as you want. basically any condition that is valid in an if statement is also valid in a filter operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.