用流替换循环以添加正确和错误拼写的单词

时间:2018-10-17 16:11:35

标签: java loops for-loop java-stream

我正在尝试使用将正确拼写的单词添加到spelledCorrectly并将错误拼写的单词添加到misspelled

的流替换此for循环。
    for (String e : incoming) {
        if (dict.contains(e.toLowerCase()))
            spelledCorrectly.add(e.toLowerCase());
        else if (!"".equals(e.toLowerCase().trim())) {
            misspelled.add(e);
        }
    }

这是我尝试过的方法,但是我在.map.collect行上遇到错误,不确定如何解决。

    incoming.stream()
        .filter(e -> dict.contains(e.toLowerCase()))
        .map(spelledCorrectly::getId)
        .collect(toList());

    incoming.stream()
        .filter(e -> !"".equals(e.toLowerCase().trim()))
        .map(misspelled::getId)
        .collect(toList());

我应该使用其他管道吗?

4 个答案:

答案 0 :(得分:0)

在上面的代码中,spell正确地和错误地拼写了循环之前已经存在的局部变量:

incoming.stream()
    .filter(e ->   dict.contains(e.toLowerCase())).forEach(e->spelledCorrectly.add(e));

incoming.stream()
    .filter(e -> !"".equals(e.toLowerCase().trim())).forEach(misspelled.add(e));

将您的循环正确转换为流

答案 1 :(得分:0)

虽然我认为nerest(看起来他/她删除了答案)答案很不错,但我决定将您的循环转换为流,

    incoming.stream()
            .filter(dict::contains)
            .forEach(spelledCorrectly::add);

    incoming.stream()
            .filter(e -> !e.isEmpty())
            .forEach(misspelled::add);

这应该和您在for循环中所做的一样

答案 2 :(得分:0)

您可以先清理单词并过滤掉空单词,然后将它们收集到一个分区中:

Map<Boolean, List<String>> result = incoming.stream()
    .map(String::trim)
    .map(String::toLowerCase)
    .filter(s -> !s.isEmpty())
    .collect(Collectors.partitioningBy(dict::contains));

答案 3 :(得分:0)

兔子是对的!但是对于正确的行为,我做了一些更新:

incoming.stream()
        .filter(dict::contains)
        .forEach(spelledCorrectly::add);

incoming.stream()
        .filter(e -> !e.isEmpty() && !dict.contains(e.toLowerCase()))
        .forEach(misspelled::add);