0

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

4 Answers 4

7

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()); 
Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

List<String> prepared = availableFieldsFromImage.stream() .map(field -> field.contains(".") ? field.split("\\.")[0] : field) .collect(Collectors.toList()); 

Comments

0

maybe

 List<String> prepared=availableFieldsFromImage.stream() .map(i->i.contains(".") ? i.split("\\.")[0] : i) .collect(Collectors.toList()) 

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
0

Use a map and then collect

availableFieldsFromImage.stream().map(field -> field.contains(".") ? field.split("\\.")[0] : field) .collect(Collectors.toList()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.