Learn how to remove first character from list of strings in Java 8 using Stream API and substring() method with examples.
Code Explanation (Step-by-Step)
- Create a list of strings using Arrays.asList() .
- Convert the list into a stream using stream().
- Use map() to transform each string in the stream.
- Apply a.substring(1) to remove the first character.
- collect(Collectors.toList()) gathers all transformed strings into a new list.
- Print the updated list that contains [“oe”, “ary”].
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CharacterTest {
public static void main(String[] args) {
List list = Arrays.asList("joe", "mary");
List names = list.stream()
.map(str -> str.substring(1))
.collect(Collectors.toList());
System.out.println("List of strings: " + names);
}
}
Output :
List of strings: [oe, ary]
Remove First Letter from List of Strings Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveFirstLetter {
public static void main(String[] args) {
List list = Arrays.asList("joe", "mary");
List result = list.stream()
.map(str -> str.replaceFirst(".", ""))
.collect(Collectors.toList());
System.out.println(result);
}
}
Here are some related Java 8 programs that will help you understand Stream API concepts better:
FAQ
Which Java 8 Stream method is used to modify elements?
The map() method is used to transform each element of a stream.
What does substring(1) do in Java?
It returns a new string starting from index 1 to the end of the string.
Can Stream API modify original list elements?
No. Stream operations create a new result unless the original collection is explicitly updated.
How do I remove the first character from a string in Java?
Use the substring(1) method.
String str = "Java";
System.out.println(str.substring(1));
Output :
ava