Sample code to convert List to List <String> in Java Stream

//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

Sample code to convert List to List <String> in Java Stream
Code to escape a JSON string in Java
[Java] Convert 1-to-N List to Map
[Android] Convert Android Java code to Kotlin
Convert a Java byte array to a string in hexadecimal notation
I tried to convert a string to a LocalDate type in Java
Java sample code 02
Java sample code 03
Java sample code 04
[Java] Convert Object type null to String type
Change List <Optional <T >> to Optional <List <T >> in Java
Convert SVG files to PNG files in Java
All same hash code string in Java
Sample code to call the Yahoo! Local Search API in Java
Java sample code 01
Sample to unzip gz file in Java
Sample code to get key JDBC type values in Java + H2 Database
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Convert to a tag to URL string in Rails
[Java] Convert DB code to code value using enum
How to write Java String # getBytes in Kotlin?
[Java] How to operate List using Stream API
[java] sort in list
Sample code to get the values of major SQL types in Java + MySQL 8.0
List processing to understand with pictures --java8 stream / javaslang-
I learned stream (I want to convert List to Map <Integer, List>)
[For beginners] Minimum sample to display RecyclerView in Java
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
Convert Java Powerpoint to XPS
Digital signature sample code (JAVA)
Java parallelization code sample collection
Convert String type to Timestamp type
Convert to Ruby Leet string
Java Stream API in 5 minutes
Java in Visual Studio Code
Write Java8-like code in Java8
[Java] Introduction to Stream API
Use Redis Stream in Java
List aggregation in Java (Collectors.groupingBy)
How to convert Java radix
[Java] Convert ArrayList to array
[Java, stream] Sort object list in Japanese by property name
Easy way to check method / field list in Java REPL
[Java] How to convert a character string from String type to byte type
How to store a string from ArrayList to String in Java (Personal)
Sample code to parse date and time with Java SimpleDateFormat
Things to be aware of when writing code in Java
List processing to understand with pictures --java8 stream / javaslang --bonus
For Java beginners: List, Map, Iterator / Array ... How to convert?
Convert 2D array to csv format with Java 8 Stream API
I wrote a code to convert numbers to romaji in TDD
Java code sample to acquire and display DBLINK source and destination data in Oracle Database using DBLINK
Sample code to get the values of major SQL types in Java + Oracle Database 12c
Guess the character code in Java
[java8] To understand the Stream API
Multithreaded to fit in [Java] template
Java Spring environment in vs Code
[Introduction to Java] About Stream API
About the method to convert a character string to an integer / decimal number (cast data) in Java
How to learn JAVA in 7 days