The accepted answer is already accepted. but I'm going to add an alternative solution with one string code;
List<UserData> userDataList = phoneNumberList.stream().filter(PhoneNumber::isPrimary) .map(UserData::new).collect(Collectors.toList());
Let's say your phone number class has several variables;
public class PhoneNumber { private String type; private String number; private boolean isPrimary; public PhoneNumber(String type, String number,boolean isPrimary) { this.isPrimary = isPrimary; this.type = type; this.number = number; }
Add your UserData I added a constructor with the Phonenumber class.which it will be easy to add your data. since I'm going to use (: :) Method Reference.
public class UserData { private String description; private String value; public UserData() { }
So let there be a list of phonenumers itearaion with one line.
List<PhoneNumber> phoneNumberList = new ArrayList<>(); phoneNumberList.add(new PhoneNumber("Landline","40054638",false)); phoneNumberList.add(new PhoneNumber("Work","90054638",true)); phoneNumberList.add(new PhoneNumber("Office","7891432654",false)); phoneNumberList.add(new PhoneNumber("Personal","40054638",true));
source share