小编spa*_*kai的帖子

在Java中实现最佳匹配搜索

我正在尝试使用现有Java数据结构获得最佳匹配字符串匹配.但这很慢,任何改善其表现的建议都会受到欢迎.

Sample数据看起来像这样

Key | V
--------------------- 
0060175559138 | VIP
--------------
006017555     | National
--------------
006017        | Local
---------------
0060          | X
--------------
Run Code Online (Sandbox Code Playgroud)

所以关键= 0060175552020的最佳匹配搜索将返回006017555

我能想到的一种方法是使用散列将多个TreeMaps转移到不同的地图中,从而使搜索区域更小.

private final TreeMap<String, V> index;

public Set<V> syncBestMatch(String key) {              
    Entry<String,V> entry = index.headMap(key, true)
                .descendingMap().entrySet().stream()
                .filter(e -> isPartiallyOrFullyMatching(key, e.getKey()))
                .findFirst()
                .orElseThrow(() -> new NoMatchException("No match found"));

    Set<V> results = new HashSet<>();
    results.add(entry.getValue());
    return results;
}
Run Code Online (Sandbox Code Playgroud)

java collections

11
推荐指数
1
解决办法
1026
查看次数

Java流.orElseThrow

我想从我一直在努力使用流的连接池项目中转换一段代码

原始代码是

for (Map.Entry<JdbConnection,Instant> entry : borrowed.entrySet()) {
  Instant leaseTime = entry.getValue();
  JdbConnection jdbConnection = entry.getKey();
  Duration timeElapsed = Duration.between(leaseTime, Instant.now());
  if (timeElapsed.toMillis() > leaseTimeInMillis) {
    //expired, let's close it and remove it from the map
    jdbConnection.close();
    borrowed.remove(jdbConnection);

    //create a new one, mark it as borrowed and give it to the client
    JdbConnection newJdbConnection = factory.create();
    borrowed.put(newJdbConnection,Instant.now());
    return newJdbConnection;
  }
}

throw new ConnectionPoolException("No connections available");
Run Code Online (Sandbox Code Playgroud)

我已经明白了这一点

borrowed.entrySet().stream()
                   .filter(entry -> Duration.between(entry.getValue(), Instant.now()).toMillis() > leaseTimeInMillis)
                   .findFirst()
                   .ifPresent(entry -> {
                     entry.getKey().close();
                     borrowed.remove(entry.getKey()); …
Run Code Online (Sandbox Code Playgroud)

java optional java-stream

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×2

collections ×1

java-stream ×1

optional ×1