0

Is there a shorter way to create sublist from other list? For example: I have a Contact obiect, this obiect contain String field of adres

public List<String> getAdreses(long personID) {
        List<String> adreses=null;
        for(Contact mail : getContacts(personID)){
            adreses.add(mail.getMail());
        }
        return adreses;
    }
2
  • Possible duplicate of How to transform List<X> to another List<Y> Commented Apr 3, 2018 at 10:20
  • @smoke, your code will not run as it is... You have initialized adreses list like... List<String>adreses = null; and later you are adding element to it like: adreses.add(mail.getMail()); But as you have not initialized adreses like: List<String> adreses=new ArrayList<>(); It will throw NullPointerException... Commented Apr 3, 2018 at 10:20

1 Answer 1

4

Try Java Stream:

List<String> adreses = getContacts(personID).stream().map(Contact::getMail).collect(Collectors.toList())
Sign up to request clarification or add additional context in comments.

2 Comments

ok, but how can i set value? in this: .map(Contact::getMail)
@smok, .map(Contact::getMail) is equal to .map(contact -> contact.getMail()) and it will collect the mails to List, you don't need to set value.

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.