Zak FST :
I have the following array of code types:
["sample_code","code","formal_code"]
and the following ids:
String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";
I want to extract the code type from the ids
this is my code snippet:
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);
it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.
for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"
Ole V.V. :
Check for the longest code types first. This means the following changes to your code:
- Sort the code types by length descending.
- Don’t use a parallel stream. A parallel stream hasn’t got an order. A sequential stream makes sure the code types are checked in order.
- Use
findFirst()
, notfindAny()
to make sure you get the first match.
So it becomes:
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);
Now output is:
sample_code