我具有以下代码类型数组:
["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"
首先检查最长的代码类型。这意味着对您的代码进行了以下更改:
使用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);
现在输出为:
样本代码