Mar*_*ius 4 java hashmap map data-structures
我想在java中为具有首选项的用户创建一个HashMap.这在数据库中很容易做到,但不幸的是我无法使用数据库.我需要的是一种在HashMap中按名称查找用户的方法,以及查找具有特定兴趣的所有用户(例如高尔夫).如果删除用户,则应删除所有兴趣.
任何人都知道制作这种数据结构的好方法吗?
B.E*_*.E. 15
我建议你创建自己的数据结构来保存信息.在该类中,您可以使用两个HashMaps存储相关信息.然后编写自己的方法来插入和删除用户.
这样,您可以控制插入/删除操作,同时可以单独查询每个属性.
你知道你真的需要第二个索引吗?除非您拥有数百万用户,否则您可能会发现对每个用户的搜索速度都很快.
以下示例需要51微秒才能扫描1,000个用户.扫描10,000个用户需要557微秒.
在您知道它是否会产生影响之前,我不会建议优化该集合.
import java.util.*;
import java.io.*;
public class TestExecutor {
public static void main(String[] args) throws IOException {
Map<String, User> users = new LinkedHashMap<String, User>();
generateUsers(users, 1000, 0.1);
// warmup.
int count = 10000;
for(int i=0;i< count;i++)
getAllUsersWithInterest(users, Interest.Golf);
long start = System.nanoTime();
for(int i=0;i< count;i++)
getAllUsersWithInterest(users, Interest.Golf);
long time = System.nanoTime() - start;
System.out.printf("Average search time %,d micro-seconds%n", time/ count/1000);
}
private static Set<User> getAllUsersWithInterest(Map<String, User> users, Interest golf) {
Set<User> ret = new LinkedHashSet<User>();
for (User user : users.values()) {
if (user.interests.contains(golf))
ret.add(user);
}
return ret;
}
private static void generateUsers(Map<String, User> users, int count, double interestedInGolf) {
Random rand = new Random();
while(users.size() < count) {
String name = Long.toString(rand.nextLong(), 36);
EnumSet<Interest> interests = rand.nextFloat() < interestedInGolf
? EnumSet.of(Interest.Golf) : EnumSet.noneOf(Interest.class);
users.put(name, new User(name, interests));
}
}
static class User {
private final String name;
private final Set<Interest> interests;
User(String name, Set<Interest> interests) {
this.name = name;
this.interests = interests;
}
}
enum Interest {
Golf
}
}
Run Code Online (Sandbox Code Playgroud)
看起来你可以使用像双向地图这样的东西来实现这样的东西.查看http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/BiMap.html了解一些doco.
虽然它不能完全满足你在问题中所需要的东西,但却只有它的一半.