首页 > 解决方案 > 如果字符串包含列表中的任何项目,JAVA 返回最长值

问题描述

我有以下代码类型数组:

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

以及以下 ID:

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

我想从 ids 中提取代码类型

这是我的代码片段:

    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,因为它返回“code”而不是“sample_code”,我想获得最长的代码类型。

for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"

标签: javajava-8java-stream

解决方案


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

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

现在输出是:

示例代码


推荐阅读