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