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;
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
Stream#map
method here
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With