JAVA返回最长的值,如果字符串包含列表中的任何项

问题描述 投票:1回答:1

我具有以下代码类型数组:

["sample_code","code","formal_code"]

和以下ID:

String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";

我想从ID中提取代码类型

这是我的代码段:

    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);

它不适用于第一个id,因为它返回的是“代码”而不是“ sample_code”,我想获得最长的代码类型。

for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"
java java-8 stream java-11
1个回答
0
投票

首先检查最长的代码类型。这意味着对您的代码进行了以下更改:

  1. 按长度降序排列代码类型。
  2. 不要使用并行流。
  3. 使用findFirst(),而不是findAny()

    String codeTypes[] = {"sample_code","code","formal_code"};
    Arrays.sort(codeTypes, Comparator.comparing(String::length).reversed());
    
    String id= "123456789_sample_code_xyz";
    Optional<String> codeType = Arrays.stream(codeTypes).filter(id::contains).findFirst();
    codeType.ifPresent(System.out::println);
    

现在输出为:

样本代码

© www.soinside.com 2019 - 2024. All rights reserved.