Elsa
Elsa

Reputation: 83

Get key-values from java object using stream collectors

I'm trying to get keys and values list from a list of objects using stream and collectorts but I don't know if it is possible.

I have this class:

public class MyObject {

    private int key1;

    private String key2;

    private String key3;

    public int getKey1() { return key1; }

    public void setKey1(int key1) { this.key1 = key1; }

    public String getKey2() { return key2; }

    public void setKey2(String key2) { this.key2 = key2; }

    public String getKey3() { return key3; }

    public void setKey3(String key3) { this.key3 = key3; }
}

I would like to process a list of this object and get all values and all keys separated by commas.

List<MyObject> objectList = myObjectList;
String keys = objectList.stream().collect(Collectors.joining(", ","(", ")"));
String values = Collections.nCopies(objectList.size(), "?").stream().collect(Collectors.joining(", ", " (", ")"));

Does anyone know if it is possible? or should I try other option?

Upvotes: 2

Views: 4617

Answers (1)

Andrew
Andrew

Reputation: 49606

For each element of a Stream<MyObject>, you can create a Stream<String>* of its keys** by the Stream#flatMap and Stream.of:

String keys = objectList
        .stream()
        .flatMap(o -> Stream.of(o.getKey1(), o.getKey2(), o.getKey3()).map(Object::toString))
        .collect(Collectors.joining(",", "(", ")"));

*Since some of the fields (keys) are not the String type, a Stream<Object> can be turned into a Stream<String> by the Stream#map(Object::toString).

**The same it is possible with values if you have getters for them.


Moving further, I would define a List of extractors (Function<MyObject, String>) for the class (there can be a static method to return this list):

public static List<Function<MyObject, String>> getExtractors() {
    return Arrays.asList(
            o -> String.valueOf(o.getKey1()),
            MyObject::getKey2,
            MyObject::getKey3
    );
}

.flatMap(o -> getExtractors().stream().map(extractor -> extractor.apply(o)))

Upvotes: 7

Related Questions