简体   繁体   中英

How to check String contains one of Strings in collection

I want to check if the target string contains string in collections. And match the longest one. Eg

Target string: str = "eignelaiwgn"

Collection strings: eig , a , eb , eigne , eignep

The result needs to be eigne

First I thought HashMap, but it is not sorted. So I try to put collection strings into ArrayList, then sort the list with string length. Then use for each loop to check

if ( str.contains("eigne") )

This needs to loop list each time. Is there a better(faster) way to achieve this?

Seems pretty straightforward with streams:

String targetString = "eignelaiwgn";
Collection<String> collection = Arrays.asList("eig", "a", "eb", "eigne", "eignep");

Optional<String> longestMatch = collection.stream()
    .filter(targetString::contains)
    .max(Comparator.comparingInt(String::length));

longestMatch.ifPresent(System.out::println); // eigne

This reads as: For every string in the collection, check if the target string contains it. If true, return the string with the max length. (As the collection might be empty, or as no string in the collection might match the filter, max returns an Optional<String> ) .

You could use a TreeSet for the same.

String str = "eignelaiwgn";
// Assuming that the 'sub-strings' are stored in a list
List<String> myList = Arrays.asList("eig", "a", "eb", "eigne", "eignep");

// Create a TreeSet that sorts based on descending order of length
Set<String> treeSet = new TreeSet<>((a, b) -> b.length() - a.length());
treeSet.addAll(myList);

String containsSub = treeSet.stream().filter(e -> str.contains(e))
                            .findFirst()
                            .orElse("Not found");

Now we iterate over the TreeSet and find the first occurrence where the sub-string is present in the original string. Now since the TreeSet is sorted in descending order of length, iteration will start from the highest to the lowest.

you can use LevensteinDistance() method of StringUtils class in java which will tell you the number of changes needed to change one String into another.you can print string with minimum changes needed, which is your answer. see this document -> LevenshteinDistance

Also look for differences method for same class which will tell the difference between the two string.

You could use a suffix tree. Please follow this link: https://www.geeksforgeeks.org/pattern-searching-using-suffix-tree/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM