java - 如果字符串包含列表中的任何项目,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"
解决方案
首先检查最长的代码类型。这意味着对您的代码进行以下更改:
- 按长度降序对代码类型进行排序。
- 不要使用并行流。并行流没有订单。顺序流确保按顺序检查代码类型。
- 使用
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);
现在输出是:
示例代码
推荐阅读
- ios - 应用程序启动时锁定为纵向从横向旋转到纵向 (iOS)
- javascript - 如何使用选择器在 DOM 下使用 Jquery 获取值
- java - 如何从java流中只返回一个字符串
- r - R中使用Plotly和Shiny的交互式散点图
- json - SQL Server - 使用 FOR JSON 的索引视图
- python - 在 Django 中用字段值的对数注释查询集
- rest - Kubernetes:什么是试运行请求?
- python - Python - 使用正则表达式从文本中提取代码
- amazon-web-services - 将 Amazon Lex 与语音助手集成
- python-3.x - 在numpy数组中获取nan值的索引