Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JAVA : how to reduce code size, when using lambda to process array's items

I must sort each item in the array, in alphabatic order

in :
[bcdef, dbaqc, abcde, omadd, bbbbb]
out :
[bcdef, abcdq, abcde, addmo, bbbbb]

I wrote the code below but i feel it verbose(long).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you please tell me an other way, with shorter code ?

Thanks.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static java.lang.String.copyValueOf;

public class Main {

    public static void main(String[] args) {
        String[] stringsArray = { "bcdef", "dbaqc", "abcde", "omadd", "bbbbb"};

        System.out.println(Arrays.toString(stringsArray));

        List<String> list = Arrays.stream(stringsArray).map((String s)->{
            char[] charArray = s.toCharArray();
            Arrays.sort(charArray);
            return copyValueOf(charArray);
        }).collect(Collectors.toList());
        ArrayList<String> arrayList = new ArrayList<String>(list);
        stringsArray = Arrays.copyOf(arrayList.toArray(),arrayList.size(),String[].class);

        System.out.println(Arrays.toString(stringsArray));
    }

}

>Solution :

It looks like you want to sort characters within each element, not the whole array.

You could simplify by having separate map() (and peek() since Arrays.sort() method is not returning a value) steps. You could also skip redundant List by collecting directly to a String array.

String[] sorted = Arrays.stream(stringsArray)
    .map(String::toCharArray)
    .peek(Arrays::sort)
    .map(String::new)
    .toArray(String[]::new);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading