返回一串所有交易者的名字,按字母顺序排序,在java8中用空格排序?

时间:2017-10-27 07:37:24

标签: java-8

我正在玩Java 8 streams并尝试按字母顺序返回所有交易者名称的字符串。

public class PuttingIntoPractice {
    public static void main(String[] args) {
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario","Milan");
        Trader alan = new Trader("Alan","Cambridge");
        Trader brian = new Trader("Brian","Cambridge");

        List<Transaction> transactions = Arrays.asList(
            new Transaction(brian, 2011, 300), 
            new Transaction(raoul, 2012, 1000),
            new Transaction(raoul, 2011, 400),
            new Transaction(mario, 2012, 710),  
            new Transaction(mario, 2012, 700),
            new Transaction(alan, 2012, 950)
        );

        // Query 4: Return a string of all traders’ names sorted alphabetically.
        String traderStr = transactions.stream()
                .map(t -> t.getTrader().getName())
                .sorted()
                .reduce("", (n1, n2) -> n1 + n2);
        System.out.println(traderStr);
    }
}

我得到的输出如下:

AlanBrianMarioMarioRaoulRaoul

我想要显示如下

 Alan Brian Mario Mario Raoul Raoul

我该怎么做?

我使用lombok生成所有锅炉板的setter getter

@Setter @Getter
@ToString
@AllArgsConstructor
public class Trader {
    private String name;
    private String city;
}

交易

@Setter @Getter 
@ToString
@AllArgsConstructor
public class Transaction {
    private Trader trader;
    private int year;
    private int value;
}

1 个答案:

答案 0 :(得分:0)

代码中的问题是如何减少Stream

正如目前所写,这个简化.reduce("", (n1, n2) -> n1 + n2);只会连接2 String而没有任何空格。要实现您的目标,您必须添加以将n1 + n2更改为n1 + " " + n2。但是,由于您希望收集 Stream的所有元素到一个String,因此您应该使用Collectors

因此,您应该将代码更改为:

String traderStr = transactions.stream()
                .map(t -> t.getTrader().getName())
                .sorted()
                .collect(Collectors.joining(" "));