【问题标题】:I would like to know how you can use in Java 8我想知道如何在 Java 8 中使用
【发布时间】:2015-12-10 14:23:40
【问题描述】:

我想知道如何在 Java 8 中使用。 我想将流用于现有句子。

List<t> selected;
List<t> filtered;

for (int count = 0; count < selected.size(); count++) {
                if(!StringUtils.endsWithIgnoreCase(selected.get(count).getBasic(), "1")) {

            for (int t = 0; t < filtered.size(); t++) {
                if (StringUtils.endsWithIgnoreCase(selected.get(count).getTitle(), filtered.get(t).getTitle())) {
                    selected.set(count, filtered.get(t));
                }
            }
        }
    }

【问题讨论】:

  • 您将不得不更好地说明您的问题。我不确定你在问什么。

标签: for-loop foreach filter java-8 java-stream


【解决方案1】:

当您修改现有的 List 时,您应该使用 List.replaceAll 而不是 Stream API。不过 Stream API 可以用来代替内部循环:

selected.replaceAll(sel ->
    StringUtils.endsWithIgnoreCase(sel.getBasic(), "1") ? sel :
      filtered.stream()
              .filter(fil -> StringUtils.endsWithIgnoreCase(sel.getTitle(), fil.getTitle())
              .findFirst()
              .orElse(sel)
);

请注意,与您的代码相比,它有点不同,因为您的内部循环不像.findFirst() 那样短路:即使找到匹配项,它也会继续在filtered 列表中搜索。如果是故意的,您应该在我的解决方案中将.findFirst() 替换为.reduce((a, b) -&gt; b) 以获得相同的结果。

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多