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 a LinkedHashMap and they are in descending order (by their digit sum). Works as expected, so far.
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). Is there a way to do this?
I am still pretty new to Java and programming in general.
My main method without the unnecessary stuff:
String filePath = args[0];
LineNumberReader br = new LineNumberReader(new FileReader(filePath));
LinkedHashMap<BigInteger, BigInteger> unsortedMap = new LinkedHashMap<BigInteger, BigInteger>();
if(br.ready()){
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
BigInteger input = new BigInteger(line);
unsortedMap.put(input, methods.digitSum(input));
}
LinkedHashMap<BigInteger, BigInteger> reverseSortedMap = new LinkedHashMap<BigInteger, BigInteger>();
unsortedMap.entrySet()
.stream()
.limit(20)
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
for (BigInteger key : reverseSortedMap.keySet()){
System.out.println(new BigDecimal(key).toPlainString() + " (Digit Sum: " + reverseSortedMap.get(key) + (")"));
}
br.close();