For instance, I have a string which contains city names and a set which also contains city names.
String line = "I love New York, but I left my heart in San Fransisco.";
Set<String> set = new HashSet<String>();
set.add("New York");
set.add("San Fransisco");
set.add("Atlanta");
I want to find and retrieve all the city names within the string which are also in the set. I tried using a complicated double for-loop. It works, but it doesn't seem efficient. Is there a better way?
for(String city1 : set){
if (set.contains(city1)){
for(String city2 : set){
if(set.contains(city2) && !city1.equals(city2)){
//inefficiently found two cities!
}
}
}
}
If you are using java 8 you can use like this to find all the city names containing in the set
String line = "I love New York, but I left my heart in San Fransisco.";
Set<String> set = new HashSet<>();
set.add("New York");
set.add("San Fransisco");
set.add("Atlanta");
set.stream().filter(line::contains).forEach(System.out::println);
Both the approaches (OP's question and @janith1024's answer) are same in time complexity- O(n*m)
; n
is the size of the set and m
is the number of characters in the string.
Which of the 2 approaches is better is a matter of preference (based on which one you feel is easier to read).
One way to get a better answer would be to be sort both the sets and compare them linearly. Then, the time complexity would be O(n log n)
where n
would be the size of the larger set. But the problem is, there is no way to break up the line
into a set. You cannot break it up as words as some cities will comprise of 2 words.
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.