Java:如何以优雅的方式将String数组从索引0连接到-2?

时间:2016-03-29 13:12:15

标签: java lambda

我将一些订单页面文件(html)提取到Java Order类,我来到下面的代码:

List<Order> orders = Files.walk(Paths.get(path, "orders", "html"))
        .map(Path::toFile)
        .map(this::readFileToString)
        .map(content -> {
            Order order = new Order();
            evaluateXPath("//*[@id='page']/div[2]/div[1]/div[3]/div[2]/span[2]/text()", content)
                    .ifPresent(x -> {
                        String[] results = x.split(" ");
                        if (results.length >= 3) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = 0; i < results.length - 2; i++) {
                                stringBuilder.append(results[i]);
                            }
                            order.setConsignee(stringBuilder.toString());
                            order.setPhoneNumber(results[results.length - 2]);
                            order.setAddress(results[results.length - 1]);
                        }
                    });
            return order;
        }).collect(Collectors.toList());


//a exception free wrapper method for FileUtils.readFileToString
private String readFileToString(File file) {
    try {
        return FileUtils.readFileToString(file);
    } catch (IOException e) {
        LOGGER.error("read " + file + " failed.");
        return "";
    }
}

private Optional<String> evaluateXPath(String xpath, String content) {
    //a mysterious implementation of evaluateXPath
}

我的问题是如何将这部分(我觉得很长很冗长)改写成更简洁的实现?

StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < results.length - 2; i++) {
    stringBuilder.append(results[i]);
}
order.setConsignee(stringBuilder.toString());

任何建议都是受欢迎的,即使它是关于我的代码的其他部分的。

2 个答案:

答案 0 :(得分:3)

Stream.of(results).limit(results.length-2).collect(Collectors.joining())

答案 1 :(得分:1)

你可以转过来:

if (results.length >= 3) {
    Deque<String> resultList = new ArrayDeque<>(Arrays.asList(results));
    order.setAddress(resultList.removeLast());
    order.setPhoneNumber(resultList.removeLast());
    order.setConsignee(String.join("", resultList));
}