Home > Enterprise >  How to split a string of delimited elements into substrings containing an equal number of elements?
How to split a string of delimited elements into substrings containing an equal number of elements?

Time:04-03

I have a very long string with prices of about 400 000 and even more..

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

Then from this very long string, I want to cut it into multiple substrings , and each sub-string should have 3 prices, example:

19, 16, 20 

01, 16, 1.3

1.6, 50, 2.0 

and more...

How do I create sub-strings each with three prices?

CodePudding user response:

This can be accomplished by splitting the string into a list containing the individual elements, partitioning that into groups of three, and then joining the elements in each partition back together.

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)).toList();

// Output each list element on a new line to view the results
System.out.println(String.join("\n", substrings));

Output:

19, 16, 20
01, 16, 1.3
1.6, 50, 2.0
17
  • Related