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

Time:02-02

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

}

CodePudding user response:

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

CodePudding user response:

If you want to modify the original array in-place, then you can rely on Arrays.asList(), which creates a List wrapper around the array:

Arrays.asList(stringsArray)
        .replaceAll(s -> {
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        });

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

Arrays.asList() is really just a view on the original array. Any change to the returned list will actually be done on the array, and vice-versa. This is also why you cannot add/remove elements on the returned list.

  •  Tags:  
  • Related