如何使用流api重写方法?

70gysomp  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(338)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

5个月前关门了。
改进这个问题
如何使用流api重写方法?

private static List<Transaction> loadTransactionFromFile () throws ParseException, IOException {

    List<Transaction> transactions = new ArrayList<>();

    List<String> lines = Files.readAllLines(Paths.get(MOVEMENT_LIST.trim()));
    lines.remove(0);

    for (String line : lines) {
        String[] fragments = line.split(",");

        if (fragments.length != 8) {
            //  System.out.println("Wrong line:s " + line);
            continue;
        }

        transactions.add(new Transaction(
                fragments[ACCOUNT_TYPE],
                fragments[ACCOUNT_NUMBER],
                fragments[CURRENCY],
                (new SimpleDateFormat(dateFormat)).parse(fragments[DATE_OF_OPERATION]
                        .trim()),
                fragments[RRN],
                fragments[INFO].replaceAll("\\d|\\\\+|\\+|RUR|MCC|(Apple Pay-)" +
                        "|\\.|\\)|\\(|RUSMOSCOW ?|MOSCOW|RUS|J|\\/RU\\/", "")
                        .trim(),
                Double.parseDouble(fragments[INCOME]),
                Double.parseDouble(fragments[EXPENSE])
        ));
    }

    return transactions;
}
eoigrqb6

eoigrqb61#

我没有测试过,但应该是这样的:

return lines.stream()
    .skip(1)
    .map(line -> line.split(","))
    .filter(l -> l.length==8)
    .map(fragments -> new Transaction(
            fragments[ACCOUNT_TYPE],
            fragments[ACCOUNT_NUMBER],
            fragments[CURRENCY],
            (new SimpleDateFormat(dateFormat))
                    .parse(fragments[DATE_OF_OPERATION]
                    .trim()),
            fragments[RRN],
            fragments[INFO].replaceAll("\\d|\\\\+|\\+|RUR|MCC|(Apple Pay-)" +
                    "|\\.|\\)|\\(|RUSMOSCOW ?|MOSCOW|RUS|J|\\/RU\\/", "")
                    .trim(),
            Double.parseDouble(fragments[INCOME]),
            Double.parseDouble(fragments[EXPENSE]))
    .collect(Collectors.toList());

相关问题