gpt4 book ai didi

Java 8 设置流循环并与数组元素进行比较

转载 作者:行者123 更新时间:2023-11-29 07:24:41 25 4
gpt4 key购买 nike

我有一个集合,其中包含 TempDTO 类型的对象列表。

public class TempDTO {
public String code;
//getter
//setter
}

Set<TempDTO> tempSet = service.getTempList();
tempSet has values whose code is ["01", "02", "04", "05"];
String[] lst = ["01", "02"]

我想循环 tempSet 将值与 lst 数组中的值进行比较,并且当值不匹配时,我需要一个值列表。输出预期是:[“04”,“05”]我试过了,

for(int i=0; i < lst.length; i++){
String st = lst[i];
tempSet.stream().forEach(obj -> {
if((obj.getCode().equals(st) )){
logger.debug(" equal " + obj.getCode());
} else {
logger.debug("not equal " + obj.getCode());
}
});
}

最佳答案

这将输出所有不匹配的值:

Set<TempDTO> tempSet = new HashSet<>(Arrays.asList(
new TempDTO("01"),
new TempDTO("02"),
new TempDTO("04"),
new TempDTO("05")));
String[] arr = new String[] { "01", "02" };

List<String> list = Arrays.asList(arr);

List<String> output = tempSet
.stream()
.filter(temp -> !list.contains(temp.getCode()))
.map(temp -> temp.getCode())
.collect(Collectors.toList());

System.out.println(output);

输出:

[04, 05]

如果您想检索 TempDTO 对象,请省略 .map(...) 调用

关于Java 8 设置流循环并与数组元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56190952/

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