我需要一个简单的数据库,比如索引搜索的结构。它将在applet中使用,因此我不想使用额外的嵌入式数据库jar。
总结: 我试着用一个神学来解释。例如学生表:
Students
------------------
Score
Gender
Name
我想过滤SCORE > 40 AND SCORE < 80 AND GENDER = MALE
我找到的解决方案进行全表扫描。但我正在寻找像TreeMap这样的解决方案。
我做了一个简单的解决方案,比如使用TreeMap进行分区。
package multikey;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class MultiKey {
public MultiKey() {
final Integer MALE = 1;
final Integer FEMALE = 2;
List<Student> students = new ArrayList<Student>();
TreeMap<Integer, TreeMap<Integer, List<String>>> table;
students.add(new Student(80, MALE, "John"));
students.add(new Student(80, FEMALE, "Monica"));
students.add(new Student(70, MALE, "Michael"));
students.add(new Student(60, MALE, "Brad"));
students.add(new Student(60, FEMALE, "Angelina"));
students.add(new Student(50, MALE, "Steve"));
students.add(new Student(40, MALE, "Alex"));
table = new TreeMap<Integer, TreeMap<Integer, List<String>>>();
for (Student student : students) {
Integer score = student.score;
Integer gender = student.gender;
TreeMap<Integer, List<String>> genderMap;
List<String> names;
if ((genderMap = table.get(score)) == null) {
genderMap = new TreeMap<Integer, List<String>>();
table.put(score, genderMap);
}
if ((names = genderMap.get(gender)) == null) {
names = new ArrayList<String>();
genderMap.put(gender, names);
}
names.add(student.name);
}
// 50 - 70 arasında alan erkekler
SortedMap<Integer, TreeMap<Integer, List<String>>> students5070 = table.subMap(50, 71);
List<String> filtered = new ArrayList<String>();
for (Integer score : students5070.keySet()) {
filtered.addAll(students5070.get(score).get(MALE));
}
System.out.println(filtered);
}
public static void main(String[] args) {
new MultiKey();
}
public class Student {
private int gender;
private String name;
private int score;
public Student(int score, int gender, String name) {
this.score = score;
this.gender = gender;
this.name = name;
}
public int getGender() {
return gender;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
@Override
public String toString() {
return name;
}
}
}
答案 0 :(得分:1)
如果您只需要一张桌子,guava tables可能会对您有所帮助,仅作为参考。如果你需要更多类似SQL的语法...我认为你不能避免使用类似纯粹的hava SQL数据库这样的东西,如HSQLDB