Dev Dev
Dev Dev

Reputation: 55

java stream joining for field which itself is a class

For a field of the same class, I can use

stream().map(String::valueOf).collect(Collectors.joining(","));

How to use the stream in one line to join id of Item from the given list of RejectItem?

class RejectItem {
    Item item;
    String reason;
}

class Item {
    Long id;
    Date createdOn;
}

// ..................

List<RejectItem> ri;
String commaSepIdString = ri.stream ??

Upvotes: 1

Views: 747

Answers (3)

Technical 101
Technical 101

Reputation: 158

You can use something like this. Don't directly use .toString() in case you have nulls as your using Long and not long.

list.stream().map(item -> String.valueOf(item.item.id)).collect(Collectors.joining(","))

I would suggest add getters and setters for your classes. Use the lombok annotation which minimise the code.

Upvotes: 2

Andreas
Andreas

Reputation: 159106

You would use a lambda expression like this:

List<RejectItem> rejectedItems = ...

String result = rejectedItems.stream()
        .map(ri -> ri.item.id.toString())
        .collect(Collectors.joining(","));

Upvotes: 3

Roland Kreuzer
Roland Kreuzer

Reputation: 992

You can use the map function also to build a "path" trough function calls, like

String commaSepIdString = ri.stream().map(ri -> ri.item).map(i -> i.id).map(String::valueOf).collect(Collectors.joining(","));

Upvotes: 1

Related Questions