大量のデータを処理しようとしていますが、最終的な計算を処理するための最良の方法に少し固執しています。
私はハッシュマップを持っています。各 Book オブジェクトには、特定のコンテキストでその本が何回表示されるかを保持する COUNT というデータ値があります。HashMap 全体を繰り返し処理し、最もよく登場する上位 10 冊の本を配列に記録したいと考えています。同時に、上位 10 冊の本を HashMap から削除したいと考えています。これを行う最善の方法は何ですか?
カウントを比較するコンパレータを使用して、マップをTreeMapなどのSortedMapにコピーします。
残りは明白なはずです。
There is a tournament algorithm that runs in O(n) time and can be useful for large data ,
Optimal algorithm for returning top k values from an array of length N
If the data is not very huge then I would recommend using Collections.sort and creating a subList from your Map.
Another option is it to keep them in TreeMap and implement Comparable in your Book Object , that way your Map is always sorted . This is particularly useful if you are doing additions to your Map as you don't want to sort them every time you change an object.
Yes, you can't remove using a for
loop because like this
for(Book curBook: yourMap.values())
You will get a ConcurrentModificationException
. To remove elements while iterating, you have to use an iterator, for example:
HashMap<Book> yourMap;
Collection<Book> entries = yourMap.values();
Iterator<Book> iterator = entries.iterator();
while(iterator.hasNext()) {
Book curBook = iterator.next();
if (yourConditionToRemove) {
iterator.remove();
}
}
If this is a frequent operation, consider using TreeMap as suggested by Bohemian or at least keep a separate Map with most read Books.
私はJavaが得意ではありませんが、次のアルゴリズムについて考えることができます。HashMap が一意の識別子に従って書籍を格納すると仮定します (つまり、 に関する順序のヒントは得られませんCOUNT
)。あなたはできる:
COUNT
ます。わかりやすくするために、このシーケンスを呼び出しますO10S
(順序付き 10 要素シーケンス)e
についてHashMap
:
O10S
まだいっぱいでない場合は挿入e
しますO10S
e
要素よりCOUNT
も大きい場合: remove from 、insert ino
O10S
COUNT
O10S
o
O10S
e
O10S
o
、からO10S
削除o
しますHashMap
アルゴリズムは、要素に関して線形HashMap
です (1 回だけトラバースする必要がありますHashMap
) 。