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.