A Y
A Y

Reputation: 177

Sorting Values in a stack in Java

I have two stacks:

public static Stack<String> listOfObjects = new Stack<String>();

public static Stack<Integer> objectCounts = new Stack<Integer>();

The stack listOfObjects contains things like:

And the stack objectCounts contains the counts for these variables at the same corresponding location in the stack

If I want to sort both stacks by the counts in the stack objectCounts, what would be the fastest way of sorting the stacks?

Thanks a lot!

Upvotes: 0

Views: 141

Answers (3)

theAlias
theAlias

Reputation: 396

"Stack" isn't the right structure to have the elements in sorted order.

But you can still try this approach,
1. Have a TreeMap < int,List < String > > //This will map to count -> list of words with the count
2. You can get the "set" of keys from the SortedMap
3. iterate through each element in set (which inherently is sorted) and push the entire list of words on to stack

Upvotes: 0

Tom
Tom

Reputation: 16198

I would instead create a Pair Object hold String name and Integer count.

private static final class Pair<K, V> {
    private final K key;
    private final V value;

    private Pair(final K key, final V value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString() {
        return "P: " + key + ", " + value;
    }
}

public static void main(final String[] args) {
    final Stack<Pair<String, Integer>> stack = new Stack<>();
    stack.add(new Pair<String, Integer>("Chair", 2));
    stack.add(new Pair<String, Integer>("Table", 2));
    stack.add(new Pair<String, Integer>("Bed", 44));
    Collections.sort(stack, new Comparator<Pair<String, Integer>>() {
        @Override
        public int compare(final Pair<String, Integer> o1, final Pair<String, Integer> o2) {
            return o2.value.compareTo(o1.value);
        }
    });
    System.out.println(stack);
}

Which returns:

[P: Bed, 44, P: Chair, 2, P: Table, 2]

You could iterate through your Stacks to create a Collections of pairs to sort quite easily to:

final Stack<Pair<String, Integer>> stack = new Stack<>();
for (int i = 0; i < stringStack.size(); i++) {
    stack.push(new Pair<String, Integer>(stringStack.get(0), countStack.get(0)); 
}

Upvotes: 2

Hugo Sousa
Hugo Sousa

Reputation: 1926

1) I'd suggest you to save that information in a class (name and count).

2) You would have to create a Comparator, where you compare it by the count of each object.

3) Do you really need to use Stack?. If you can implement it with Array or something, there's a built-in method to sort it, using a Comparator, that you've defined.

If you really need to use Stack, I would copy the elements to an Array, sort it, and then copy to a Stack again.

Also, consider using a PriorityQueue.

Upvotes: 0

Related Questions