繁体   English   中英

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

[英]Java 8 set stream loop and compare with array elements

我有一个包含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());
  }
  });    
}

您可以使用:

// convert array(lst) to arrayList
List<String> arrList = Arrays.asList(lst);

// now check if the values are present or not
List<String> nonDupList = tempSet.stream()
                                  .filter(i -> !arrList.contains(i.getCode()))
                                  .map(TempDTO::getCode)
                                  .collect(Collectors.toList());

输出:

[05,04]

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

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(...)调用

您必须执行以下步骤。

  1. 获取所有这样的代码列表:

     List<String> allCodesList = tempSet.stream() .map(value -> value.getCode()) .collect(Collectors.toList()) ; 
  2. 您已经有了第二个列表。

  3. 检查boolean result = Arrays.equals(allCodesList.toArray(),lst.toArray());

这将为您提供所有列表中没有代码的所有TempDTO对象

tempSet = tempSet.stream()
            .filter( obj -> !Arrays.stream( lst ).anyMatch( str -> str.equals( obj.getCode() ) ) )
            .collect( Collectors.toSet() );

我建议使用过滤器方法,首先创建一个辅助列表以使用包含方法,创建一个函数以获取所需的值(代码),然后使用谓词过滤辅助列表中未包含的值,最后收集列表中的值

// create an auxiliar list 
List<String> auxLst = Arrays.asList(lst);

// map to code
Function<TempDTO, String> map = t -> t.getCode();
// condition
Predicate<String> lstNotcontains = code -> !auxLst.contains(code);

List<String> missingValues = tempSet.stream().map(map).filter(lstNotcontains).collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM