I have a List of String and I would like to append text in front of each String in the list. I am trying to achieve this without a for/Iterator loop like a single line of code. I can't find a solution to this.
Following I have tried with a for loop but need solution without this. Is there a solution?
List<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("b");
strings.add("c");
strings.add("d");
List<String> appendedList = new ArrayList<String>();
for (String s : strings) {
appendedList.add("D" + s);
}
Please help. Thanks.
If you're using Java 8, then you can use the newly added replaceAll
method to do this:
strings.replaceAll(s -> "D"+s);
Here's a full working example:
import java.util.Arrays;
import java.util.List;
public class StringTest {
public static void main(String[] args) {
List<String> strings = Arrays.asList("a", "b", "c", "d");
strings.replaceAll(s -> "D"+s);
System.out.println(strings);
}
}
You could also use the new Streams API to do this, but slightly more verbosely, making a copy of the list instead of mutating (updating) the original list:
List<String> strings = Arrays.asList("a", "b", "c", "d");
strings = strings.stream()
.map(s -> "D"+s) // Using Lambda notation to update the entries
.collect(Collectors.toList());
System.out.println(strings);
Note that I used Arrays.asList()
to create the list more succinctly. This isn't a new feature in Java 8, so you should be able to use it in Java 5/6/7 as well. Here's my output:
$ java StringTest
[Da, Db, Dc, Dd]
Even if you're not using Java 8 right now, it's still good to note that these features have been added, and if you run into a similar problem in a year or two then you can use something from the new API!
Something like this perhaps
public List<String> recursiveAdd(List<String> strings, List<String> finalList, String prepender){
if(strings == null || strings.size() == 0) return finalList;
else{
finalList.add(prepender + strings.remove(0));
return recursiveAdd(strings,finalList,prepender);
}
}
strings = recursiveAdd(strings, new ArrayList<String>(), "D");
This is more a functional solution, the problem with the above code is that strings will be destroyed inside the class you can make a deep copy before calling the recursive operation if you want to avoid that!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With