How to make a new list with a property of an object which is in another list

前端 未结 6 1161
借酒劲吻你
借酒劲吻你 2020-12-22 16:49

Imagine that I have a list of certain objects:

List

And I need to generate another list including the ids of

6条回答
  •  抹茶落季
    2020-12-22 17:27

    With Guava you can use Function like -

    private enum StudentToId implements Function {
            INSTANCE;
    
            @Override
            public Integer apply(Student input) {
                return input.getId();
            }
        }
    

    and you can use this function to convert List of students to ids like -

    Lists.transform(studentList, StudentToId.INSTANCE);
    

    Surely it will loop in order to extract all ids, but remember guava methods returns view and Function will only be applied when you try to iterate over the List
    If you don't iterate, it will never apply the loop.

    Note: Remember this is the view and if you want to iterate multiple times it will be better to copy the content in some other List like

    ImmutableList.copyOf(Iterables.transform(students, StudentToId.INSTANCE));
    

提交回复
热议问题