2

The model:

public class MyModel{
    private int id;
    private String name;
    ....
    ....
    //getters and setters
}

I have a list of MyModel object:

//First Object to be added to list
MyModel myModelObject1 = new MyModel();
myModelObject1.setId(1);
myModelObject1.setName("abc");

//Second Object to be added to list
MyModel myModelObject2 = new MyModel();
myModelObject1.setId(2);
myModelObject1.setName("pqr");

List<MyModel> myModelList = new ArrayList<MyModel>();
myModelList.add(myModelObject1);
myModelList.add(myModelObject2);

I want to get a list of names present in the MyModel List i.e. I want to create a list of names (List<String> in this case) from myModelList. So, I want my list to have:

{"abc", "pqr"}

There is always a way to iterate and create another list but is there any better way to do that? (Not necessarily to be efficient but if it can be done in a line using streams, foreach e.t.c.).

EDIT: The answers worked for me but I have some modifications in my use case: If I want to add a condition that only name which contains character 'a' should be added to the list and I want to add a logger message to debug for each element then how should I approach this?

I tried doing the following using a method (charAPresent()) which checks that if the passed String contains character 'a' but it didn't work:

List<String> modelNameList = myModelList.stream()
        .map(model -> {
            if (charAPresent(model.getName)) {
                model.getName() 
            }
        })
        .collect(Collectors.toList());

Let me know if I am missing something.

4 Answers 4

4

Using Java 8 Stream:

List<String> modelNameList = myModelList.stream()
                                 .map(Model::getName)
                                 .collect(Collectors.toList());

Model::getName is called as method reference. It equivalents to model -> model.getName()

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Dinh Tien Loc, That works, but I ran into one more situation in this use case. If I have to add a condition that only name which contains char 'a' should be aadded to list (In this case list will have {"abc"}, then how should I do that? I am pretty new in Java8.
@SiddharthShankar You can use filter method in stream. myModelList.stream().map(Model::getName).filter(name -> name.contains("a")).collect(Collectors.toList())
2

You can use streams and map your object to its name and collect to a list as:

List<String> names = myModelList.stream()
        .map(MyModel::getName)
        .collect(Collectors.toList());

There is always a way to iterate and create another list but is there any better way to do that

Even with the use of streams, you would have to iterate the complete collection. There is no better way of doing it than iterating the complete collection.

Comments

1

You can use Stream.map() to get only the names of your model. Use Stream.filter() to get only the names matching your charAPresent() method. To log the entries before collecting you can use Stream.peek():

List<String> modelNameList = myModelList.stream()
        .map(Model::getName) // map only the name
        .filter(YourClass::charAPresent) // filter the items
        .peek(System.out::println) // print all items which are in the filter
        .collect(Collectors.toList());

Comments

0

You can also use foreach like this:

public static List<String> modelNames(List<MyModel> myModelList)
    List<String> list = new ArrayList<String>();
    for(MyModel mm : myModelList) {
        if(mm.getName().contains("a") {
            list.add(mm.getName());
        }
    }
    return list;
}

Comments

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.