Sort and split data based on dynamic sequential ordered input stream in java

I want to sort the elements and group them as follows. How can I achieve this using the sort, group and java thread section on.

The input enters the streams, which means that after receiving the lower input, after some time an input may occur, such as A16.17, the data structure should be reorganized and regrouped.

Input A10, A4, A11, A3, A12, A15 .... B19, B2, B20 ...

Output A3-A4, A10-A12, A15, B2, B19-B20.

I could sort as below

array.sort(Comparator   .comparing(...)
                                .thenComparing(Comparator.comparing(...)));

but not sure how to split and regroup to input strings using streams in the most optimized way.

 array.stream().collect(Collectors.partitionBy(...))

What should be the logic in the function for the section in above to achieve the grouping of consecutive orders?

+4
1

, Comparator Collector, Java8 Stream:

array.stream().sorted(new MyComparator()).collect(new MyCollector());

Comparator :

class MyComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        if(s1.substring(0, 1).compareTo(s2.substring(0,1)) < 0) {
            return -1;
        } else if (s1.substring(0, 1).compareTo(s2.substring(0,1)) > 0) {
            return 1;
        } else { //first char is equal
            if(Integer.parseInt(s1.substring(1, s1.length())) < Integer.parseInt(s2.substring(1, s2.length()))) {
                return -1;
            } else if (Integer.parseInt(s1.substring(1, s1.length())) > Integer.parseInt(s2.substring(1, s2.length()))) {
                return 1;
            }
        }
        return 0;
    }
}

, . A10, A11... A2,A3... 1<2.

Collector , , .

Collector, , List, List, , .

+1

Source: https://habr.com/ru/post/1680852/


All Articles