//Class of elements to put in List
public class MyData {
public final String name;
public final Integer age;
public MyData(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getMyInfo() {
return name + "(" + age + ")";
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
//Build data
List<MyData> list = new ArrayList<>() {
{
add(new MyData("Alice", 88));
add(new MyData("Bob", 8));
add(new MyData("Carol", null));
add(null);
}
};
//Conversion example 1
List<String> list1 = list.stream() //Create Stream object
.filter(Objects::nonNull) //Exclude null elements
.map(MyData::getMyInfo) //Generate a string for each element
.collect(Collectors.toList()); //List
System.out.println(String.join("\n", list1));
//Conversion example 2
List<String> list2 = list.stream() //Create Stream object
.filter(Objects::nonNull) //Exclude null elements
.map(mydata -> mydata.name + ": " + mydata.age) //Generate a string for each element
.collect(Collectors.toList()); //List
System.out.println(String.join("\n", list2));
//Conversion example 3
List<String> list3 = list.stream() //Create Stream object
.filter(Objects::nonNull) //Exclude null elements
.map(mydata -> { //Generate a string for each element
if (mydata.age == null) {
return mydata.name;
} else {
return mydata.name + ": " + mydata.age;
}
})
.collect(Collectors.toList()); //List
System.out.println(String.join("\n", list3));
}
}
Execution result by Java 15 (AdoptOpenJDK 15 + 36).
$ javac *.java
$ java Main
Alice(88)
Bob(8)
Carol(null)
Alice: 88
Bob: 8
Carol: null
Alice: 88
Bob: 8
Carol
Reference: Stream \ (Java Platform SE 8 )
Recommended Posts