简体   繁体   中英

Storing data for a linked list in a pair in Java

I am trying to create a linked list that will take a large amount of data, either integers or strings, and get the frequency that they occur. I know how to create a basic linked list that would achieve this but since the amount of data is so large, I want to find a quicker way to sort through the data, instead of going through the entire linked list every time I call a certain method. In order to do this I need to make a Pair of <Object, Integer> where the Object is the data and the integer is the frequency it occurs.

So far I have tried creating arrays and lists that would help me sort out the data but cannot figure out how to get it into a Pair that represents the data and frequency. If you have any ideas that can help me at least get started that would be much appreciated.

First of all you must define your own data type, let's say

public FrequencyCount<T> implements Comparable<FrequencyCount<T>>
{
  public final T data;
  public int frequency;

  public int compareTo(FrequencyCount<T> other) {
    // implement this method to choose your correct natural ordering
  }
}

With a similar object everything becomes trivial:

List<FrequencyCount<Some>> data = new ArrayList<FrequencyCount<Some>>();
Collections.sort(data);

Set<FrequencyCount<Some>> sortedData = new TreeSet<FrequencyCount<Some>>(data);

You could place all values into a List, create a Set from it and then iterate over the Set to find the frequency in the List using Collections.frequency: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#frequency(java.util.Collection,%20java.lang.Object)

List<Integer> allValues = ...;
Set<Integer> uniqueValues = new HashSet<Integer>(allValues);
for(Integer val : uniqueValues) {
    int frequency = Collections.frequency(allValues, val);
// use val and frequency as key and value as you wish
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM