0

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();
HeartCore
  • 49
  • 5
  • 1
    Welcome Mr.HeartCore, If possible, could you please attach your program here so we can help you to correct it since we can get clear picture from your program than the description. – Ganesa Vijayakumar Oct 14 '19 at 11:28
  • @GanesaVijayakumar I'm sorry. Added it! – HeartCore Oct 14 '19 at 11:41
  • I cannot think of a way of doing that with streams right know, but after you have sorted them on their digitSum, you can interate through the map again, and where the value is the same, check the key value, also and swap them if necessary – Andrei Tigau Oct 14 '19 at 13:18
  • @AndreiTigau so how could this be done? – HeartCore Oct 15 '19 at 07:14

0 Answers0