[英]java- how to extract words and files into a set?
我正在用Java创建一个简单的算法,该算法将从数据库表中提取单词以及它们各自的文件,并将其保存在一个集合或数组中。
例如,这就是我的表的样子:
path word
file1 w1
file1 w2
file1 w3
.........
file2 w2
file2 w5
.........
这样的例子不胜枚举。
在我的程序中,我想从表中提取这些数据,以便将其存储在这样的集合中:
w1={file1}
w2={file1, file2}
w3={file1}
w5={file2}
...... and etc
当然,表中肯定会有更多数据,但这只是我要完成的工作的总体思路。
我要做的第一步是建立与数据库的JDBC连接,并从表中运行select语句。 但是,我不知道如何像上面描述的那样提取它们来存储它们。
我应该使用数组还是hashSet还是其他?
我将不胜感激任何建议。
您可以使用HashMap<String,TreeSet<String>> map = new HashMap<>();
然后您的代码将是:
ResultSet rs = stmt.executeQuery("SELECT PATH, WORD FROM TABLE_A");
while(rs.next()) {
if (map.containsKey(rs.getString("WORD"))) { // If the word is already in your hash map
TreeSet<String> path = map.get(rs.getString("WORD")); //get the set of files where this word exist
path.add(rs.getString("PATH")); // add the new path to the set
map.put(rs.getString("WORD"), path); // update the map
} else { // else if the word is new
TreeSet<String> path = new TreeSet<String>(); // create a new set
path.add(rs.getString("PATH")); // add the path to the set
map.put(rs.getString("WORD"), path); // add the new data to the map
}
}
在这种情况下, TreeSet比HashMap更好,因为它不接受重复的值,因此保证了更高的完整性。
不管怎么说,HashMap中更好地适合您的需要,导致路径可以是键字值。
我准备了一个示例,说明如何检索路径和单词,然后将它们分别放入HashMap的键和值中:
Map<String, String> fileParameters = new HashMap<>();
ResultSet rs = stmt.executeQuery("SELECT path, word FROM files");
while(rs.next()) {
String path = rs.getString("path");
String name = rs.getString("word");
fileParameters.put(path, name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.