Add key and value to priority queue and sort by key in Java

I am trying to take a list of strings and add them to a priority queue with key and value. The key is the word and the value is the string value of the word. Then I need to sort the queue with the highest row value first. The priority queue prevents me from adding 2 values.

public static List<String> pQSortStrings(List<String> strings) {
    PriorityQueue<String, Integer> q = new PriorityQueue<>();

    for (int x = 0; x < strings.size(); x++) {
        q.add(strings.get(x),calculateStringValue(strings.get(x)));
    }
    return strings;
}

      

+3


source to share


1 answer


Problem

PriorityQueue

can store one node object in it. So what you are trying to do cannot be done the way it is.

But you can link both objects in one class and then use PriorityQueue

.

You will need to provide Comparator

or rely on natural ordering by implementing an Comparable

interface.




Decision

  • Create a class with String

    and int

    as members.

    public class Entry {
        private String key;
        private int value;
    
        // Constructors, getters etc.
    }
    
          

  • Implement the interface Comparable

    and map the delegate to String

    .

    public class Entry implements Comparable<Entry> {
        private String key;
        private int value;
    
        public Entry(String key, int value) {
            this.key = key;
            this.value = value;
        }
    
        // getters
    
        @Override
        public int compareTo(Entry other) {
            return this.getKey().compareTo(other.getKey());
        }
    }
    
          

  • Build PriorityQueue

    with this class.

    PriorityQueue<Entry> q = new PriorityQueue<>();
    
          

  • Add the following items.

    q.add(new Entry(strings.get(x), calculateStringValue(strings.get(x))));
    
          

Hope it helps.

+8


source







All Articles