0

Edit More detailed Description of the function:

I have a HashSet filled with a specific object named Symbol. A specific function iterates through all Symbols. The function specify the energy cost of every single Symbol and return this. I want to make a new Set/Map and save the Symbols in it, ordered by this energy cost. The next algorithm takes the Symbol with the biggest energy cost and put it in another List which is limited in cases of energy cost. When this List is full, the algorithm ends.

What should I use to save the energy cost and the Symbol? I should be able to get the energy cost and the Symbol.

I thought about a SortedMap and order it through the guava.collection like here:

https://stackoverflow.com/a/3420912

But i don't know if this is the best solution? Maybe a Set would be better for this kind of problem?

Community
  • 1
  • 1
YKilic
  • 33
  • 3

2 Answers2

0

If I have understood what you want to do, what you need is:

  • Ensure your Symbol class implements the Comparable interface.
  • Instead a Set (HashSet), use a SortedSet (TreeSet).

If a Set fulfills your needings, don't change to a Map, keep it simple ;). Maps are useful when you need random access.

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

If you want to extract maximum on each step, you should look at heap data structure. In Java Collections class implementing heap is PriorityQueue.
If you want to extract maximum, you should provide your own comparator to constructor, like this:

PriorityQueue<Symbol> pq = new PriorityQueue<Symbol>(0, new Comparator<Symbol>(){     
    @Override
    public int compare(Symbol s1, Symbol s2) {
        if (s1.getLong() < s2.getLong()) {
             return 1;
        } else if (s1.getLong() > s2.getLong()) {
             return -1;
        } else {
             return 0;
        }
    }
});

Take a look, how comparator works. It should return -1 if s1 is lesser than s2, but PriorityQueue extracts minimum value, not maximum, so we invert this behavior.
Of course, if you just want to iterate over data once and don't insert anything in it keeping maximum at the head, then @Pablo answer is better.

mkrakhin
  • 3,386
  • 1
  • 21
  • 34