gpt4 book ai didi

java - 重复项不会添加到列表中

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:13:35 26 4
gpt4 key购买 nike

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

 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;
}
}

}

最佳答案

不清楚为什么您希望重复项消失,因为您实际上没有做任何事情来删除它们。

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

更新:写

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

关于java - 重复项不会添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com