简体   繁体   中英

Map values collect to string with streams

I implemented toString for HashMap field as following:

public class Bar {
    private HashMap<String, Foo> m = null; // Foo is a class with defined toString method

    @Override
    public String toString() {
        String eol = System.getProperty("line.separator");
        final String[] ret = {""};
        m.forEach( (k,v) -> ret[0] += v + eol);
        return ret[0];
    }
}

How to implement this function with java 8 streams? The following is a samples of my unsuccessful tryes (just for illustration what I want to)

m.values().stream().collect(Collectors.joining()).
m.entrySet().stream().collect(Collectors.joining()).toString();

You can use .map function to transform every Map.Entry set to a String representation. Using .map function you can focus on how each line of an output should look like and after that you can create a result with .collect(Collectors.joining(eol)) call. Below you can find an example that produces your desired output:

@Override
public String toString() {
    final String eol = System.getProperty("line.separator");
    return m.values()
            .stream()
            .map(Foo::toString)
            .collect(Collectors.joining(eol));
}

Exemplary output:

[foo:something1]
[foo:something2]
[foo:something3]

UPDATE:

It seems like you have changed the desired output. Anyway the whole idea is to provide a function in .map() that does the transformation from Foo object to its String representation. All other parts are still valid.

UPDATE 2:

Answer updated to satisfy updated expectations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM