Sam*_*ire 5 java algorithm search set
如果我有很多组字符串,并且每个字符串都有不同的项目,并且其中一些项目有重叠的项目。
我想搜索作为搜索集中所有项目的并集的集合。
我可以用哈希做些什么吗?
联盟是否找到了正确的算法?
这是我想要的布隆过滤器吗?
equals在下面的示例中,我可以首先依靠HashSet检查是否存在精确匹配。
我搜索每组并执行containsAll以查看它是否与搜索集并集。
举个例子,如果我用[“橙色”,“猕猴桃”,“苹果”]设置“水果”,用[“卷心菜”,“胡萝卜”,“西兰花”]设置“蔬菜”。我想要搜索 [“orange”、“kiwi”] 来匹配“fruits”
一定有比这更好的方法,但我不确定。
package main;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class SetKeyHash {
public static void main(String args[]) {
HashSet<String> vegetables = new HashSet<>();
vegetables.add("tomato");
vegetables.add("carrot");
vegetables.add("broccoli");
HashSet<String> fruit = new HashSet<>();
fruit.add("apple");
fruit.add("kiwi");
fruit.add("orange");
Map<HashSet<String>, String> map = new HashMap<>();
map.put(vegetables, "vegetables");
map.put(fruit, "fruit");
HashSet<String> search = new HashSet<>();
search.add("tomato");
search.add("carrot");
search.add("broccoli");
System.out.println("Exact set search");
System.out.println(map.get(search));
System.out.println("Partial set search");
HashSet<String> partialSearch = new HashSet<>();
partialSearch.add("tomato");
partialSearch.add("broccoli");
for (HashSet<String> set : map.keySet()) {
if (set.containsAll(partialSearch)) {
System.out.println(String.format("Found partial match %s", map.get(set)));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你需要用Map<String, HashSet<String>> map = new HashMap<>();它来代替。
以下解决方案查找包含“搜索”集中所有元素的所有集名称。
HashSet<String> vegetables = new HashSet<>();
vegetables.add("tomato");
vegetables.add("carrot");
vegetables.add("broccoli");
HashSet<String> fruit = new HashSet<>();
fruit.add("apple");
fruit.add("kiwi");
fruit.add("orange");
Map<String, HashSet<String>> map = new HashMap<>();
map.put("vegetables", vegetables);
map.put("fruit", fruit);
HashSet<String> search = new HashSet<>();
search.add("tomato");
search.add("carrot");
//search.add("broccoli");
Set<String> nameOfSets = map.entrySet().stream()
.filter(entry -> entry.getValue().containsAll(search))
.map(Map.Entry::getKey).collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1070 次 |
| 最近记录: |