Joining a collection based on members of the type

842 views Asked by At

I have a class A and its members b and c. Now I construct the List<A> with this:

add(new A().setb("abcd").setc("123456"));
add(new A().setb("efgh").setc("789101"));
add(new A().setb("ijkl").setc("112345"));

I want to transform this List to string which looks like this

abcd,123456
efgh,789101
ijkl,112345

Now the very obvious way would be to have a StringBuilder and iterate across the List. Now I want to establish this using Guava Joiner like

Joiner.on("\n").skipNulls().join(.......)

the join() method expects an iterable. Can I somehow pass A.getb(),A.getc() Will Iterables.transform help?

2

There are 2 answers

0
Abhiroop Sarkar On BEST ANSWER

Solved it!!

Lets say the List<A> is called Alist

String join=Joiner.on("\n").skipNulls().join(Iterables.transform(Alist, new Function<A,String>(){
            public String apply(A input){
                return input.getb()+","+input.getc();
            }
        }));
4
Sotirios Delimanolis On

With Java 8, you can use

String result = as.stream().map((a) -> a.b + ',' + a.c).collect(Collectors.joining("\n"));

which first generates a String from each A element in the List, then collects it into a String by joining the individual String values with a new line character.

With Guava, you get something similar with

String result = Joiner.on('\n').join(Iterables.transform(as, (a) -> a.b + ',' + a.c));

assuming as is your List<A>.