优雅的方法克服equals()的不太可能的参数类型:Stream <String>似乎与String无关

Vis*_*tna 5 java java-8 java-stream

我正在寻找优雅的方法来比较任何Wrapper对象和Stream.

Github工作链接:https://github.com/vishwaratna/Unlikely-argument-type-for-equals-Stream-String-/commit/d803f77c923e81fe7531ecb467561ac785d7aca5

参考问题:在java-8中过滤从map到list属性的键

最近我在比较List一个关键的成员时面对它Map.我知道有其他方法可以比较而不做我正在做的事情,但我正在寻找一般铸造,如果它可用.

List<student> stulist = Arrays.asList(new student("1", "vishwa",null),
                                              new student("3", "Ravi",null),
                                              new student("2", "Ram",null));
Run Code Online (Sandbox Code Playgroud)
        Map<String,String> map = new HashMap() {{
             put("1","20");
             put("2","30");
           }};
Run Code Online (Sandbox Code Playgroud)
System.out.println( stulist.stream()
                    .filter(s->s.getId()
                    .equals(map.entrySet()
                    .stream() 
                    .map(Map.Entry::getKey)))
                    .count());
Run Code Online (Sandbox Code Playgroud)

我的代码编译正确,但输出为"0",而我期望输出为2.

我确定这是由于类型不匹配,但为什么编译器没有 抛出错误?

警告我得到: Unlikely argument type for equals(): Stream<String> seems to be unrelated to String

Nam*_*man 2

首先,您可能想要的可能是:

System.out.println(stulist.stream()
        .filter(s -> map.keySet().contains(s.getId()))
        .count());
Run Code Online (Sandbox Code Playgroud)

equals其次,代码中使用的比较是不正确的,因为它是在两种不同类型的String和 的对象之间进行的Stream<String>

// here the 's.getId' is a String while 'map.entrySet()...map()' provides 'Stream<String>'
.filter(s -> s.getId().equals(map.entrySet().stream().map(Map.Entry::getKey)))
Run Code Online (Sandbox Code Playgroud)

  • @CommonMan `.filter(s -&gt; map.keySet().contains(s.getId()))` 与您的过滤器所做的完全不同。不过,如果输出不是您想要的,您能否补充一下您还想进一步寻找什么的问题? (2认同)
  • @CommonMan不太确定将“Stream”转换为“String”是什么意思,您是否想加入它们? (2认同)