Skip to content
Advertisement

How to partition a string and read data from all the partitions?

I am working on a big string of prices which I want to cut into small groups, then from those small groups I want to read these values: firstPrice, lastPrice, highPrice and lowPrice.

So far I have the following code:

String s_prices = getString(R.string.testing).trim();

// 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 += i_timeframe) {
            partitions.add(prices.subList(i, Math.min(i + i_timeframe, 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());
//
        Comparator<String> numberValueComparator = Comparator.comparing(BigDecimal::new);
        for (List<String> p : partitions) {
            high = Float.parseFloat(Collections.max(p, numberValueComparator).replace(";", "").trim());
            low = Float.parseFloat(Collections.min(p, numberValueComparator).replace(";", "").trim());
            first= Float.parseFloat(p.get(0).replace(";", "").trim());
            last= Float.parseFloat(p.get(p.size() - 1).replace(";", "").trim());
        }

I am successfully getting what I want, but now I want to adjust the code a little bit. What I want now is, instead of getting first price on every partition, I want the last price of the previous partition to be the first price of the current partition. see examples bellow: {1;2;3;4} {4;5;6;7} {7;8;9;10} {10;11;12;13} {13;14;15;16} {16;17;18;19} and more…

As you can see from the example given above, the last price of a previous partition is the first price of the following partition.

For now with the above code I am getting these: {1;2;3;4} {5;6;7;8} {9;10;11;12} {13;14;15;16} {17;18;19;20} …,

The last price of the previous partition is not equal/same with the first price of following partition.

My question is, how do I edit my code so that I get what I want?

Advertisement

Answer

Making a minor modification in your partitioning logic should do the trick.

Note: I’ve added -1 in the increment section of the for loop.

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