进入列表中的几行

时间:2018-08-13 10:56:44

标签: java java-8 java-stream

我上了简单的课:

public class ForStream {
   private int shortId;
   private long longId;

public ForStream(int shortId, long longId) {
    this.shortId = shortId;
    this.longId = longId;
}

public int getShortId() {
    return shortId;
}

public void setShortId(int shortId) {
    this.shortId = shortId;
}

public long getLongId() {
    return longId;
}

public void setLongId(long longId) {
    this.longId = longId;
}
}

有必要查找数组中多个子字符串的出现。我这样做(可能无效):

  public static void main(String[] args) {
    List<ForStream> resList = List.of(
            new ForStream(689, 10000000001L),
            new ForStream(781, 10000000001L),
            new ForStream(785, 10000000001L),
            new ForStream(689, 10000000002L),
            new ForStream(689, 10000000003L),
            new ForStream(781, 10000000004L),
            new ForStream(785, 10000000004L)
    );

    boolean isEqual = !resList.stream()
            .filter(p -> p.getLongId() == 10000000001L)
            .filter(p -> p.getShortId() == 689)
            .filter(p -> p.getShortId() == 781)
            .filter(p -> p.getShortId() == 785)
            .collect(Collectors.toList()).isEmpty();

}

返回false。但是列出了689、781和785。

1 个答案:

答案 0 :(得分:2)

这应该有效。您正在过滤单个元素。但是,您希望将其与值列表进行比较。您正在做的是&&,但您需要做的是||

   boolean isEqual = !resList.stream()
                .filter(p -> p.getLongId() == 10000000001L)
                .filter(p -> Arrays.asList(689, 781, 785).contains(p.getShortId()))
                .collect(Collectors.toList()).isEmpty();