Home > Enterprise >  How to find highest and lowest value on substrings?
How to find highest and lowest value on substrings?

Time:04-03

I have this code:

String s_prices = "19; 16; 20; 01; 16; 1.3; 1.6; 50; 2.0; 17";

// Convert to List of strings:
// ["19", "16", "20", "01", "16", "1.3", "1.6", "50", "2.0", "17"]
        List<String> prices = Arrays.asList(s_prices.split("; "));

// Convert to List of 3-element lists of strings (possibly fewer for last one):
// [["19", "16", "20"], ["01", "16", "1.3"], ["1.6","50", "2.0"], ["17"]]
        List<List<String>> partitions = new ArrayList<>();
        for (int i = 0; i < prices.size(); i  = 3) {
            partitions.add(prices.subList(i, Math.min(i   3, prices.size())));
        }

// Convert each partition List to a comma-delimited string
// ["13, 16, 20", "01, 16, 1.3", "1.6, 50, 2.0", "17"]
        List<String> substrings = partitions.stream().map(p -> String.join(", ", p)).collect(Collectors.toList());


// Output each list element on a new line to view the results
        System.out.println(String.join("\n", substrings));
        TextView tv = findViewById(R.id.pprices);
        tv.setText(String.join("\n", substrings ));

and I want to find the highest and the lowest price on every substring and show results on TextView as follows

19, 16, 20  High: 20, Low: 16
01, 16, 1.3  High: 16, Low: 01
1.6, 50, 2.0  High: 50, Low: 1.6
17  High: 17, Low: 17

CodePudding user response:

The Collections.max and Collections.min methods return the largest/smallest element in a list. These can be used while mapping the partitions list with Stream.map to return the results in the format you're looking for:

Comparator<String> numberValueComparator = Comparator.comparing(BigDecimal::new);
List<String> groupedValue = partitions.stream()
        .map(p -> String.format("%s  High: %s, Low: %s",
                String.join(", ", p),
                Collections.max(p, numberValueComparator),
                Collections.min(p, numberValueComparator)))
        .toList();

System.out.println(String.join("\n", groupedValue));

Output:

19, 16, 20  High: 20, Low: 16
01, 16, 1.3  High: 16, Low: 01
1.6, 50, 2.0  High: 50, Low: 1.6
17  High: 17, Low: 17

Note that it's important to compare the numeric value of the string, rather than the string itself. For instance, using the natural order of strings, "1001" < "17". This is why this is using a Comparator that first converts the number to a BigDecimal using the BigDecimal(String) constructor, and then compares those values.

  • Related