类型 List<String> 中的方法 get(int) 不适用于 Java 中的参数字符串 8

The method get(int) in the type List<String> is not applicable for the argument string in Java 8

我正在尝试搜索 List<String> 中的元素,但出现此编译错误:

the method get(int) in the type List<String> is not applicable for the argument string.

这是代码:

private boolean findIdInTheList(List<String> ids, String id) {
    String theId = ids.stream()
            .filter(elem -> id.equals(ids.get(elem)))
            .findAny()
            .orElse(null);
}

idsList<String>elemString。因此 ids.get(elem) 无效,因为 List 没有采用 String.

get 方法

应该是:

private boolean findIdInTheList(List<String> ids, String id) {
    String theId = ids.stream()
                      .filter(elem -> id.equals(elem))
                      .findAny()
                      .orElse(null);
}

哦,因为你的方法有一个 boolean return 类型,你应该添加一个 return 语句。

您可以使用 anyMatch 简化管道:

private boolean findIdInTheList(List<String> ids, String id) {
    return ids.stream()
              .anyMatch(elem -> id.equals(elem));
}

这里你得到一个 boolean,表示是否在 List 中找到了 id。我认为 returning String 本身没有意义,因为您已经知道它等于 id.

.filter(elem -> id.equals(elem))

您已经从 Predicate

中的来源获得了 elem

也可以写成方法参考:

.filter(id::equals) 

.filter(elem -> id.equals(ids.get(elem)))这里是错误的,你已经完成了ids.stream()这意味着idsids的所有元素)已经被转换成流并存在以通过或失败 filter().

现在你正在应用一个 filter() 这是一个谓词并且将 return bool(true or false).

现在你只需要将你的字符串元素与流值进行比较,你不需要通过 get().

再次进入列表

为了更好地理解不同的方法:

List<String> ids = Arrays.asList("Vishwa","Eran","Eugene","gaby","nullpointer");
String id = "gaby";
Predicate<String> pre = (p1)->p1.equals("gaby");
String theID = ids.stream().filter(s->pre.test(id)).findAny().orElse(null);

上面网友(Eran和Eugene)说的完全正确,我赞同他们,我只是想根据我的理解添加更清楚的解释。