Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections Sort to sort both ArrayLists the same

My program has to use the Collections sort method to sort the ArrayList of Strings lexicographically but each String has a corresponding integer value stored in a separate ArrayList. I want to sort them both the same so the integer values stay with the correct Strings. And if you know a better way to store both values I'm all ears.

public class a5p1b {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in).useDelimiter("[^a-zA-z]+");
        // ArrayLists to store the Strings and the frequencies
        ArrayList<String> lst = new ArrayList<String>();
        ArrayList<Integer> intLst = new ArrayList<Integer>();

        //loops through as long as there is user input
        while (input.hasNext()) {
            String str = input.next().toLowerCase();
            // if the list already has the string it doesn't add it and it
            // ups the count by 1
            if (lst.contains(str)) {
                int index = lst.indexOf(str);
                intLst.set(index, intLst.get(index) + 1);
            } else {
                // if the word hasnt been found yet it adds it to the list
                lst.add(str);
                intLst.add(1);
            }
        }
    }    
}
like image 421
Alex Hutchings Avatar asked Jul 25 '26 16:07

Alex Hutchings


1 Answers

You are getting your abstractions wrong. If that string and that number belong together, then do not keep them in two distinct lists.

Instead create a class (or maybe use one of the existing Pair classes) that holds those two values. You can then provide an equals method for that class; plus a specific comparator, that only compares the string elements.

Finally, you put objects of that class into a single list; and then you sort that list.

The whole idea of good OO programming is to create helpful abstractions!

For the record: as dnault suggests, if there is really no "tight" coupling between strings and numbers you could also use a TreeMap (to be used as TreeMap<String, Integer>) to take care of sorting strings that have a number with them.

like image 193
GhostCat Avatar answered Jul 28 '26 07:07

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!