Suresh
Suresh

Reputation: 515

Need Help on Java 8 stream logic

I have an array list containing multiple strings. I need to replace one of the item in that list with updated value based on some condition and retain other strings. I need help in doing Java 8's way.

Code Sample:

String newPONumber = "Orig PO#: 22222222222222456";
List<String> existingMessages = Arrays.asList("Orig PO#: 2222222222222222    ", "this is a sample string     ");
List<String> updatedMessages =  new ArrayList<>();
System.out.println("Existing Messages");
existingMessages.stream().forEach(System.out::println);


//Java 8's way that I tried but losing the existing messages since filter is used
updatedMessages = existingMessages.stream()
        .filter(message -> message != null)
        .map(String :: trim)
        .map(String:: toUpperCase)
        .filter(message -> message.startsWith("ORIG"))
        .map(message -> newPONumber)
        .collect(Collectors.toList());

System.out.println("New Messages");
updatedMessages.stream().forEach(System.out::println);

Output should contain all the message plus the updated Orig PO# string

//"Orig PO#: 2222222222222456", "this is a sample string"

Traditional for loop way

for(String message : existingMessages) {
    message = message.trim();
    if(message.startsWith("ORIG")) {
        message = newPONumber;
    }
    updatedMessages.add(message);                   
} 

Upvotes: 4

Views: 89

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56433

What you're looking for is replaceAll:

existingMessages.replaceAll(s -> s == null ? s : s.trim().toUpperCase().startsWith("ORIG") ? newPONumber : s.trim());

or if you don't want to modify existingMessages:

List<String> updatedMessages = new ArrayList<>(existingMessages);
updatedMessages.replaceAll(s -> s == null ? s : s.trim().toUpperCase().startsWith("ORIG") ? newPONumber : s.trim());

Upvotes: 2

Naman
Naman

Reputation: 31878

One way to do that would be

List<String> updatedMessages = existingMessages.stream()
        .filter(Objects::nonNull)
        .map(String::trim)
        .map(message -> message.toUpperCase().startsWith("ORIG") ? newPONumber : message)
        .collect(Collectors.toList());

Notice: The toUpperCase is only applicable within the condition and is not on the resultant string as in your traditional for loop solution.

Upvotes: 1

Related Questions