gpt4 book ai didi

java - 表式索引集合过滤

转载 作者:行者123 更新时间:2023-12-01 15:23:48 25 4
gpt4 key购买 nike

我需要一个简单的类似数据库的结构来进行索引搜索。它将在小程序中使用,因此我不想使用额外的嵌入式数据库 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;
}
}
}

最佳答案

如果您只需要一张 table ,guava tables或许对你有帮助,仅供引用。如果您需要更多类似 SQL 的语法...我认为您无法避免使用像 HSQLDB 这样的纯 hava SQL 数据库之类的东西。

关于java - 表式索引集合过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10477354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com