How to match elements in different arrays in Java

I have two ArrayLists: a list of strings and an integer list. For instance:

Bob        2
Kevin      6
Lane       4
Susan      2
//the ArrayLists will have more elements

I am trying to sort an integer ArrayList (with MergeSort) and have a String ArrayList for an integer ArrayList, for example:

Susan      2
Bob        2
Lane       4
Kevin      6

Other answers I received advise using Map (key int, value String); however, I cannot do this because there will be duplicate keys.

I read about Guava Multimap; however it is not very convenient for me to include jar files in classpaths.

Is there any other way to do this?

+4
source share
2 answers

, - ints, Java, , :

public class MyClass implements Comparable<MyClass> {
    private String myString;
    private int myInt;

    public MyClass(String s, int x) {
        myString = s;
        myInt = x;
    }

    public int getInt() {
        return myInt;
    }

    public String getString() {
        return myString;
    }

    public void setInt(int x) {
        myInt = x;
    }

    public void setString(String s) {
        myString = s;
    }

    // this method is the only method defined in the Comparable<T> interface
    // and is what allows you to later do something like Collections.sort(myList)

    public int compareTo(MyClass other) {
        return myInt - other.getInt();
    }
}

List<MyClass> ls = new ArrayList<MyClass>();, .

, Comparable, , Java, Collections.sort(), Collections, , . , , .

+4

- , :

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

public class ExStringArraySort {

    static HashMap<String, Integer> mapPerson = new HashMap<String, Integer>();
    static String[] prsn;

    public static void main(String[] args) {
        // Add persons
        mapPerson.put("Bob", 2);
        mapPerson.put("Kevin", 6);
        mapPerson.put("Lane", 4);
        mapPerson.put("Susan", 2);

        String[] prsn = mapPerson.keySet().toArray(new String[mapPerson.size()]);

        Arrays.sort(prsn);
        System.out.println(Arrays.toString(prsn));

        System.out.println("Print detail:");
        for (int i = 0; i < prsn.length; i++) {
            System.out.println(prsn[i]+"\t"+mapPerson.get(prsn[i]));
        }

        Arrays.sort(prsn, Collections.reverseOrder());
        System.out.println("\n"+Arrays.toString(prsn));
        System.out.println("Print detail:");
        for (int i = 0; i < prsn.length; i++) {
            System.out.println(prsn[i]+"\t"+mapPerson.get(prsn[i]));
        }

    }

}

:

[Bob, Kevin, Lane, Susan]
Print detail:
Bob 2
Kevin   6
Lane    4
Susan   2

[Susan, Lane, Kevin, Bob]
Print detail:
Susan   2
Lane    4
Kevin   6
Bob 2
0

Source: https://habr.com/ru/post/1679395/


All Articles