1

I have this LinkedHashMap containing Integer indexes and object Paire for values :

Map<Integer, Paire> population1 = new LinkedHashMap<>();

My Paire class is rather simple and looks like this :

 public class Paire {

     float valeur;
     int index;

 public Paire(LinkedList<Sommet> liste, float valeur, int index) {

    this.liste = liste;
    this.valeur = valeur;
    this.index = index;
}

Now I want to store a keyset of my map, sorted by the float value from my class (valeur), in a LinkedList :

List<Integer> selection1 = new LinkedList(population1.keySet());

I know I could use Collection.sort to sort values and then track back their respective keys if those values were simple Strings or numbers, but I'm a little lost here. I feel there are simple and fast ways to do this without intermediate lists and variables. In addition, my code's execution needs to be as fast as possible (genetic algorithm for TSP).

2
  • Why dont you use a SortedMap with a comparator? Commented Jun 29, 2017 at 20:39
  • 1
    @LeonardBrünings SortedMap doesn't work with sorting values. Commented Jun 29, 2017 at 20:41

2 Answers 2

1
Collections.sort(selection1, new Comparator<Integer>() {
  @Override public int compare(Integer key1, Integer key2) {
    return Float.compare(
         population1.get(key1).valeur, population1.get(key2).valeur);
  }
});

If you care about speed, though, LinkedList is never your friend. Use ArrayList.

Sign up to request clarification or add additional context in comments.

1 Comment

Works incredibly well! Thanks. I do a lot of getFirst() and removeFirst(), this is why I use LinkedList. Thanks for the advice anyway!
0

I recommend using stream (in my opinion, it is should be much faster then Collections.sort):

List<Integer> list = population1.entrySet().stream().sorted((e1, e2) -> Float.

compare(e1.getValue().valeur,e2.getValue().valeur)).map(Map.Entry::getKey)

  .collect(Collectors.toList());

I do a lot of getFirst() and removeFirst(), this is why I use LinkedList.

Better revert order of ArrayList and you can use:

    list.get(list.size() - 1)

instead of

 getFirst()

and

 list.remove(list.size() - 1)

instead of

 removeFirst()

Because getting and deleting last element of ArrayList is very very fast.

P.S. LinkedList is very very slow in almost any case

1 Comment

This is a nice advice, I really thought LinkedList was only slower for insertion and looking for items in the middle of the list. The tip for getting and deleting faster with ArrayList is also very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.