Skip to content
Advertisement

Java. Best way to split each element of List

How can I optimize this using streams ?

    List<String> prepared = new ArrayList<>();
    availableFieldsFromImage.forEach(field -> {
        if(field.contains(".")){
            prepared.add(field.split("\.")[0]);
        } else {
            prepared.add(field);
        }
    });

Advertisement

Answer

split returns the initial string if the delimiter is not found, so there is no need to test for “.” before performing the split:

List<String> prepared = availableFieldsFromImage.stream()
                        .map(field -> field.split("\.")[0])
                        .collect(Collectors.toList());
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement