Which is the best data structure to store duplicate values in java? And how easy is to retrieve values from it!?
thanks EDIT #1 I am reading contents from 1000 files, and I want to put each files content as tokens in some data structure. I used Hashtable but i am not able to view many words when I am doing that. thats why I want a data structure which can 开发者_运维问答store the duplicate values.
For just storing simple values, you should use an implementation of the List<E>
interface.
To get data from a List<E>
you can do the following:
list.get(index); // will get data at a given index
// or you can iterate over all of the items in the list
for(E item: list) {
// use E
}
Depending on your use either an ArrayList<E>
or LinkedList<E>
will do what you need.
Another option would be a Map<K, V>
(it's implementation HashMap
). This will allow you to save duplicate values under unique keys.
You can get values out of a Map<K,V>
in the following ways:
map.get(someKey); // will retrieve the value associated with a key
// or you can iterate through all of the entries in a map like so:
for(Entry<K,V> entry: map.entrySet()){
// use entry
}
Response to your edit:
You may want to use a Map<String, List<String>>
where the key is the name of the file, and the value is a list of the words in the file.
Your code may look like this:
Map<String, List<String>> data = new HashMap<String, List<String>>();
for(File f: files) {
List<String> words = new ArrayList<String();
data.put(f.getName(), words);
Scanner s = new Scanner(f);
while(s.hasNext()) {
words.add(s.next());
}
}
At the end of this snipit, data
will be filled with lists of words from each file.
theres lack of info to properly answer this qn.. but anyway, hashmaps could do the trick. retrieval of values can be done in constant time on average..
You should use List<E>
but you should implement a int[] getDuplicateValuesIndexes(String value)
method and a int getCount(String value)
. These will be useful because in List<E>
implementations, there are nothing to treat duplicate values as they store just values of any kind.
Any java.util.Collection that does not implement the Set interface. Probably you'll want something that implements a List.
Use Arrays, to get value use index (I know its incomplete answer, but so is the question)
精彩评论