JAVA return longest value if a string contains any of the items from a List

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:

  1. Sort the code types by length descending.
  2. 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.
  3. Use findFirst(), not findAny() 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=4311&siteId=1