--Concatenate strings returned by multiple objects in the List --Use java.util.stream.Stream introduced from Java 8
MyData.java
/**
*Represents key-value data.
*/
public class MyData {
private final String k;
private final String v;
public MyData(String key, String val){
this.k = key;
this.v = val;
}
public String key(){
return k;
}
public String val(){
return v;
}
}
Main.java
import java.util.ArrayList;
import java.util.Comparator;
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<MyData>() {
{
add(new MyData("KEY", "VALUE"));
add(null);
add(new MyData("Key", "value"));
add(new MyData("Key", "Baryu"));
add(new MyData("key", "value"));
add(null);
add(new MyData("key", null));
}
};
//Create and process Stream objects
String s = list.stream()
.filter(Objects::nonNull) //Exclude null elements
.filter(myData -> myData.val() != null) //Exclude null values
.sorted(Comparator.comparing(MyData::key).reversed()) //Reverse sort by key
.map(myData -> myData.key() + ":" + myData.val()) //Generate a string for each element
.collect(Collectors.joining(", ")); //Concatenate strings
//Output concatenated string
System.out.println(s);
}
}
$ javac *.java
$ java Main
key:value,Key:value,Key:Baryu, KEY:VALUE
Recommended Posts