Java 8 stream join and return multiple values

后端 未结 4 1368
时光说笑
时光说笑 2020-12-17 22:32

I\'m porting a piece of code from .NET to Java and stumbled upon a scenario where I want to use stream to map & reduce.

class Content
{
  private String          


        
4条回答
  •  醉梦人生
    2020-12-17 22:59

    static Content merge(List list) {
        return new Content(
                list.stream().map(Content::getA).collect(Collectors.joining(", ")),
                list.stream().map(Content::getB).collect(Collectors.joining(", ")),
                list.stream().map(Content::getC).collect(Collectors.joining(", ")));
    }
    

    EDIT: Expanding on Federico's inline collector, here is a concrete class dedicated to merging Content objects:

    class Merge {
    
        public static Collector collector() {
            return Collector.of(Merge::new, Merge::accept, Merge::combiner, Merge::finisher);
        }
    
        private StringJoiner a = new StringJoiner(", ");
        private StringJoiner b = new StringJoiner(", ");
        private StringJoiner c = new StringJoiner(", ");
    
        private void accept(Content content) {
            a.add(content.getA());
            b.add(content.getB());
            c.add(content.getC());
        }
    
        private Merge combiner(Merge second) {
            a.merge(second.a);
            b.merge(second.b);
            c.merge(second.c);
            return this;
        }
    
        private Content finisher() {
            return new Content(a.toString(), b.toString(), c.toString());
        }
    }
    

    Used as:

    Content merged = contentList.stream().collect(Merge.collector());
    

提交回复
热议问题