重复项目未添加到列表

时间:2016-10-17 22:19:30

标签: java lambda java-8 java-stream

我正在尝试下面的java代码,并希望根据输入列表将所有匹配项添加到列表中。下面是输入列表,查找列表和返回匹配列表。 Currenlty,当我们在输入列表中有重复值时,下面的代码失败。有人可以建议我如何解决这个问题吗?提前谢谢。

 import java.time.YearMonth;
 import java.util.*;
 import static java.util.stream.Collectors.toList;


public class PeriodTest {

public static void main(String[] args) {

    //Input
    List<YearMonth> yearMonths = Arrays.asList(YearMonth.of(2016, 9), YearMonth.of(2016, 9));

    //Look up
    List<PeriodCode> periodCodes = Arrays.asList(new PeriodCode(2016, 9), new PeriodCode(2017, 9));

    //Code
    List<PeriodCode> actualOutput = periodCodes.stream().filter(item -> yearMonths.contains(YearMonth.of(item.getYear(), item.getMonth()))).collect(toList());
    List<PeriodCode> expectedOutput = Arrays.asList
            (
                    new PeriodCode(2016, 9),
                    new PeriodCode(2016, 9)
            );

    System.out.print(actualOutput.size() == expectedOutput.size());//false 1 vs 2

}

private static class PeriodCode {

    private int year;
    private int month;

    PeriodCode(int year, int month) {
        this.year = year;
        this.month = month;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof PeriodCode)) return false;

        PeriodCode that = (PeriodCode) o;

        if (year != that.year) return false;
        return month == that.month;

    }

    @Override
    public int hashCode() {
        int result = year;
        result = 31 * result + month;
        return result;
    }

    int getYear() {
        return year;
    }

    void setYear(int year) {
        this.year = year;
    }

    int getMonth() {
        return month;
    }

    void setMonth(int month) {
        this.month = month;
    }
}

}

1 个答案:

答案 0 :(得分:2)

目前尚不清楚为什么你会发现重复消失,因为你实际上并没有做任何事情来删除它们。

.distinct()添加到流链可能会有所帮助。

更新:写

periodCodes.stream()
    .flatMap(periodCode -> 
        yearMonths.stream()
            .filter(YearMonth.of(periodCode.getYear(), periodCode.getMonth())::equals)
            .map(ym -> periodCode))
    .collect(toList())