Converting a generic list to a string list using Java streams
Java 8 lambda create list of Strings from list of custom class objects - Stack Overflow
java - Using streams to convert a list of objects into a string obtained from the toString method - Stack Overflow
Convert Stream<Object[]> to List<Object> using java stream - Stack Overflow
You need to collect your Stream into a List:
List<String> adresses = users.stream()
.map(User::getAdress)
.collect(Collectors.toList());
For more information on the different Collectors visit the documentation.
User::getAdress is just another form of writing (User user) -> user.getAdress() which could as well be written as user -> user.getAdress() (because the type User will be inferred by the compiler)
It is extended your idea:
List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
.collect(Collectors.toList())
One simple way is to append your list items in a StringBuilder
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
StringBuilder b = new StringBuilder();
list.forEach(b::append);
System.out.println(b);
you can also try:
String s = list.stream().map(e -> e.toString()).reduce("", String::concat);
Explanation: map converts Integer stream to String stream, then its reduced as concatenation of all the elements.
Note: This is normal reduction which performs in O(n2)
for better performance use a StringBuilder or mutable reduction similar to F. Böller's answer.
String s = list.stream().map(Object::toString).collect(Collectors.joining(","));
Ref: Stream Reduction
There is a collector joining in the API.
It's a static method in Collectors.
list.stream().map(Object::toString).collect(Collectors.joining(","))
Not perfect because of the necessary call of toString, but works. Different delimiters are possible.
List<Object> flat = objArrs.stream()
.flatMap(Stream::of)
.collect(Collectors.toList());
or
List<Object[]> list = ...
List<Object> l = list.stream()
.flatMap(arr -> Stream.of(arr))
.collect(Collectors.toList());
How about this? you can using Stream#flatMap to merge all of Student[] in a List together.
stream.flatMap(students-> Stream.of(students)).collect(Collectors.toList());
The documentation says:
The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream.
Java 8
You could map them all to Strings first and then group by the tuple (modelId, serviceId) and only then map the results of the grouping to the dtos.
import java.util.Arrays;
import java.util.stream.Collectors;
List<MyDto> myDtos = queryResult.stream()
// cast all to String and put into tuple
.map(objects -> Arrays.asList((String) objects[0], (String) objects[1], (String) objects[2]))
// group by tuple (modelid, serviceId)
.collect(Collectors.groupingBy(r -> Arrays.asList(r.get(1), r.get(2)),
Collectors.mapping(r -> r.get(0), Collectors.toList())))
.entrySet().stream()
.map(entry -> new MyDto(entry.getKey().get(0), entry.getKey().get(1), entry.getValue()))
.collect(Collectors.toList());
Bonus points for Java 14+
To increase readability instead of using lists we introduce records
import java.util.List;
import java.util.Map;
record MyDto(String vehicleId, String modelId, List<String> serviceIds) {
public MyDto(Map.Entry<AggregateKey, List<String>> vehiclesAggregate) {
this(vehiclesAggregate.getKey().modelId(), vehiclesAggregate.getKey().serviceId(),vehiclesAggregate.getValue());
}
}
record ResultRow(String vehicleId, String modelId, String serviceId) {
public ResultRow(Object[] entries) {
this((String) entries[0], (String) entries[1], (String) entries[2]);
}
public AggregateKey getKey() {
return new AggregateKey(modelId, serviceId);
}
}
record AggregateKey(String modelId, String serviceId) {}
Resulting in a much shorter and very readable streaming pipeline
import java.util.List;
import java.util.stream.Collectors;
List<MyDto> myDtos = queryResult.stream()
.map(ResultRow::new)
.collect(Collectors.groupingBy(ResultRow::getKey,
Collectors.mapping(ResultRow::vehicleId, Collectors.toList())))
.entrySet().stream()
.map(MyDto::new)
.toList(); // shorthand for collect(Collectors.toList) since Java 16
If you don't necessarily need to use stream, you can always use a standard cycle, for example:
Map<String, MyDTO> myDTOs = new HashMap<>();
for(Object[] a : listOfObjectArrays) {
String key = a[1] + " - " + a[2];
MyDTO myDTO = myDTOs.get(key);
if(myDTO == null) {
List<String> vehicleIds = new ArrayList<>();
vehicleIds.add((String) a[0]);
myDTO = new MyDTO((String) a[1], (String) a[2], vehicleIds);
myDTOs.put(key, myDTO);
} else {
myDTO.getVehicleIds().add((String) a[0]);
}
}
List<MyDTO> myDTOList = new ArrayList<>(myDTOs.values());
How can I convert list containing object A to list containing object B. Object A has a method to convert it to object. What is the elegant way in Java 8?
The following code block does not work, but how I make it to work.
protected List<B> getAllB(List<A> alist) {
return alist.stream().forEach(s -> s.toADto());
}