1

Is there a way to search String inside the Set using regex?
For example i want to search AAA*B in hash set, and expecting the result AAAAB,AAB etc..

If there is no such a thing, what would you suggest to use instead of hash set ?

It is similar question to how to search data as sql like?

Abdullah Tellioglu
  • 1,434
  • 1
  • 10
  • 26
  • As per my knowledge there is nothing any inbuilt like operator for list in java. The closest thing you can do is iterate your structure(in your case set) and for each object use `matches` method. Have a look http://stackoverflow.com/questions/898405/how-to-implement-a-sql-like-like-operator-in-java – Dhruv Pal Mar 20 '17 at 09:41
  • Below link might help you. It looks like same solution what you want to have. It might be duplicate. [http://stackoverflow.com/questions/39674216/how-to-use-regular-expression-while-searching-in-hashset](http://stackoverflow.com/questions/39674216/how-to-use-regular-expression-while-searching-in-hashset) – Arindam Mar 20 '17 at 09:42

2 Answers2

2

HashSet certainly won't get you anywhere. It's designed for very efficient exact lookups, but completely useless for fuzzy lookups, as it doesn't have any concept of ranges or proximity.

There is no standard data structure that supports search like that. You could implement part of this functionality yourself by using the NavigableSet interface (TreeSet being the standard implementation).

But ideally, you would need to use something like a Radix tree, which is not a standard Java data structure.

Of course you could still implement it in a brute force way using a HashSet, iterating over all entries and checking each of them against your pattern. But your performance will be O(n) instead of O(1), so there will be no benefits of using a HashSet (apart from eliminating duplicates) and you might as well use an ArrayList.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

For sure you can but not out of the box...you can combine Streams and regex in a filter:

for example, imagine you have a set f strings and you need/want only the ones that not numeric:

Set<String> languages = new HashSet<>(Arrays.asList("0", "java", "c++", "1234", "1999"));
Set<String> resultFilteredLanguages = languages.stream().filter(line -> !line.matches("\\d+")).collect(Collectors.toSet());
resultFilteredLanguages.forEach(System.out::println);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97