Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Projection of containers, i.e. method to transform List<Object> to List<Object.Member>

I have a List of Objects, lets say List<Example> and the class Example has a member a which is a String:

class Example {
    String a;
    String b;
}

Now I would like to get from List<Example> to List<String> by using only the a elements from each member of the list.

Of course this is easy to do with a loop, but I was trying to find something similar to the algorithms in C++ which could do this directly.

Question: What is the simplest way to project from List to List, in which the values are the field a of Example?


Edit: this is what I meant by for loop:

List<String> result = new ArrayList<String>();
for(Example e : myList)
    result.add(e.a);
return result;
like image 781
Beginner Avatar asked May 11 '17 13:05

Beginner


2 Answers

Here's a simple solution using Java 8's declarative stream mapping:

class Example {
    String a;
    String b;
    // methods below for testing
    public Example(String a) {
        this.a = a;
    }
    public String getA() {
        return a;
    }
    @Override
    public String toString() {
        return String.format("Example with a = %s", a);
    }
}
// initializing test list of Examples
List<Example> list = Arrays.asList(new Example("a"), new Example("b"));

// printing original list
System.out.println(list);

// initializing projected list by mapping
// this is where the real work is

List<String> newList = list
    // streaming list
    .stream()
    // mapping to String through method reference
    .map(Example::getA)
    // collecting to list
    .collect(Collectors.toList());

// printing projected list
System.out.println(newList);

Output

[Example with a = a, Example with a = b]
[a, b]

Docs

  • General package API on Java 8 streams here
  • Specific API on Stream#map method here
like image 168
Mena Avatar answered Oct 17 '22 03:10

Mena


You can use streams in java8

List<Example> l = Arrays.asList(new Example("a", "a"), new Example("b", "b"), new Example("c", "c"),
               new Example("d", "d"));
List<String> names = l.stream().map(Example::getA).collect(Collectors.toList());
System.out.println(names);
like image 2
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 17 '22 01:10

ΦXocę 웃 Пepeúpa ツ