How do I sort two ArrayLists and put them in a Map?

HeartCore :

My program calculates the digit sums of all values entered into a text file. The entered values and their according digit sums are stored in two seperate ArrayLists.

Both ArrayLists are combined into a LinkedHashMap in the end which should be ordered by the digit sum in descending order. If you enter multiple values with the same digit sum, it's supposed to order those (and only those) in descending order by their original value, not the digit sum this time (the rest stays the same as before).

How do I achieve this with Comparators?

My lists and the map:

String filePath = args[0];

LineNumberReader br = new LineNumberReader(new FileReader(filePath));
LinkedHashMap<BigInteger, BigInteger> unsortedMap = new LinkedHashMap<BigInteger, BigInteger>();
List<BigInteger> inputList = new ArrayList<>();
List<BigInteger> DSList = new ArrayList<>();

if(br.ready()){
     while (true) {
        String line = br.readLine();
        if (line == null) {
            break;
        }

        BigInteger input = new BigInteger(line);
        inputList.add(input);
        DSList.add(methods.digitSum(input));

    }
}

for(int i = 0; i < inputList.size(); i++){
    unsortedMap.put(inputList.get(i), DSList.get(i));
}

for(BigInteger key : unsortedMap.keySet()){
    System.out.println(new BigDecimal(key).toPlainString() + " (Digit Sum: " + unsortedMap.get(key) + (")"));
}

methods.digitSum:

public static BigInteger digitSum(BigInteger number) {

        String digits = number.toString();
        int sum = 0;

        for(int i = 0; i < digits.length(); i++) {
            int digit = (int) (digits.charAt(i) - '0');
            sum = sum + digit;
        }

        return BigInteger.valueOf(sum);

}

Output has to look like this:

x (digit sum: y)
x (digit sum: y)
...
x = entered value
y = digit sum of x

If you need any further information, feel free to ask.

Joakim Danielson :

Here is a solution with a simple class and a Comparator

class Values {
    BigInteger number;
    BigInteger digitSum;

    Values(BigInteger number, BigInteger sum) {
        this.number = number;
        this.digitSum = sum;
    }

    @Override
    public String toString() {
        return number + " (digit sun:" + digitSum + ")";
    }
}

And then create a list with this class

 List<Values> inputList = new ArrayList<>();

and add objects of Values to the list using the constructor when reading the file

For sorting you can create a Comparator object like this

Comparator<Values> compareSum = (Values v1, Values v2) -> {
   int result = v1.digitSum.compareTo(v2.digitSum);
   return result != 0 ? result : v1.number.compareTo(v2.number);           
};

and sort your list in descending order

inputList.sort(compareSum.reversed());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306198&siteId=1