Java - map a list of objects to a list with values of their property attributes

后端 未结 8 1807
星月不相逢
星月不相逢 2020-12-01 01:28

I have the ViewValue class defined as follows:

class ViewValue {

private Long id;
private Integer value;
private String description;
private View view;
priv         


        
8条回答
  •  没有蜡笔的小新
    2020-12-01 01:53

    Use google collections. Example:

        Function transform = new Function() {
            @Override
            public Long apply(ViewValue from) {
                return from.getId();
            }
        };
        List list = Lists.newArrayList();
        List idsList = Lists.transform(list, transform);
    

    UPDATE:

    On Java 8 you don't need Guava. You can:

    import com.example.ViewValue;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    Function transform = ViewValue::getId;
    List source = new ArrayList<>();
    List result = source.stream().map(transform).collect(Collectors.toList());
    

    Or just:

    List source= new ArrayList<>();
    List result = source.stream().map(ViewValue::getId).collect(Collectors.toList());
    

    NEXT UPDATE (The last one after Javaslang to Vavr name change):

    Currently it's worth to mention about the solution with Javaslang library(http://www.javaslang.io/) Vavr library (http://www.vavr.io/). Let's assume that we have our list with genuine objects:

    List source = newArrayList(new ViewValue(1), new ViewValue(2), new ViewValue(2));
    

    We could make transformation with List class from Javaslang library (on the long run the collect is not convenient):

    List result = io.vavr.collection.List.ofAll(source).map(ViewValue::getId).toJavaList();
    

    But you will see the power with only the Javaslang lists:

    io.vavr.collection.List source = javaslang.collection.List.of(new ViewValue(1), new ViewValue(2), new ViewValue(3));
    io.vavr.collection.List res = source.map(ViewValue::getId);
    

    I encourage to take a look available collections and new types on that library (I like especially the Try type). You will find the documentation under the following address: http://www.javaslang.io/javaslang-docs/ http://www.vavr.io/vavr-docs/.

    PS. Due to the Oracle and the "Java" word within the name they had to change the library name from javaslang to something else. They had decided to Vavr.

提交回复
热议问题