Java String lines()

Introduction

The String.lines() method, introduced in Java 11, provides an easy way to split a string into a stream of lines. Each line is separated based on line terminators such as \n (newline) or \r\n (carriage return followed by newline). This method is particularly useful for reading multi-line strings and processing each line independently.

The lines() method returns a Stream<String>, which can be further processed using the powerful Stream API operations like filtering, mapping, or collecting.

Solution Steps

  1. Create a Multi-Line String: Start by creating a string that contains multiple lines.
  2. Use lines() Method: Call the lines() method on the string to get a stream of lines.
  3. Process the Stream: You can iterate through the lines or perform operations like filtering, collecting, or printing.
  4. Display the Output: Print each line or process it based on the required logic.

Java Program

Example 1: Basic Usage of lines()

public class StringLinesExample {
    public static void main(String[] args) {
        // Step 1: Create a multi-line string
        String text = "Java is fun.\nJava is powerful.\nJava 11 introduced new features.";

        // Step 2: Use the lines() method to get a stream of lines
        text.lines().forEach(System.out::println);
    }
}

Output

Java is fun.
Java is powerful.
Java 11 introduced new features.

Explanation

  • Step 1: Create a Multi-Line String
    A string text is created with three lines, separated by newline characters (\n):
String text = "Java is fun.\nJava is powerful.\nJava 11 introduced new features.";
  • Step 2: Use lines() Method
    The lines() method splits the string into individual lines, each one separated by newline characters. The result is a Stream<String>:
text.lines().forEach(System.out::println);

Here, we use the forEach() method to print each line in the stream.


Example 2: Using lines() with Stream Operations

import java.util.List;
import java.util.stream.Collectors;

public class StringLinesStreamExample {
    public static void main(String[] args) {
        // Step 1: Create a multi-line string
        String text = "Java is fun.\nJava is powerful.\nJava is evolving.\n";

        // Step 2: Use lines() to get a stream and filter out lines containing "fun"
        List<String> filteredLines = text.lines()
            .filter(line -> line.contains("fun"))
            .collect(Collectors.toList());

        // Step 3: Display the filtered lines
        filteredLines.forEach(System.out::println);
    }
}

Output

Java is fun.

Explanation

  • Step 1: Create a Multi-Line String
    A string text is created, and it contains multiple lines, similar to the previous example.

  • Step 2: Filter the Stream of Lines
    The lines() method splits the string into individual lines and returns a Stream<String>. The stream is then filtered using the filter() method to only retain lines that contain the word "fun":

List<String> filteredLines = text.lines()
    .filter(line -> line.contains("fun"))
    .collect(Collectors.toList());
  • Step 3: Display the Filtered Lines
    Finally, the filtered lines are collected into a list and printed using forEach():
filteredLines.forEach(System.out::println);

Example 3: Counting the Number of Lines in a String

public class StringLinesCountExample {
    public static void main(String[] args) {
        // Step 1: Create a multi-line string
        String text = "First line\nSecond line\nThird line";

        // Step 2: Count the number of lines in the string
        long lineCount = text.lines().count();

        // Step 3: Display the count
        System.out.println("Number of lines: " + lineCount);
    }
}

Output

Number of lines: 3

Explanation

  • Step 1: Create a Multi-Line String
    We create a multi-line string text containing three lines:
String text = "First line\nSecond line\nThird line";
  • Step 2: Count the Number of Lines
    The lines() method is used to get a stream of lines, and the count() method counts the number of lines:
long lineCount = text.lines().count();
  • Step 3: Display the Count
    Finally, the program prints the number of lines in the string.

Example 4: Collecting Lines into a List

import java.util.List;

public class StringLinesToListExample {
    public static void main(String[] args) {
        // Step 1: Create a multi-line string
        String text = "Apple\nBanana\nCherry";

        // Step 2: Collect the lines into a List
        List<String> fruits = text.lines().collect(Collectors.toList());

        // Step 3: Display the List
        System.out.println(fruits);
    }
}

Output

[Apple, Banana, Cherry]

Explanation

  • Step 1: Create a Multi-Line String
    We create a multi-line string with the names of fruits:
String text = "Apple\nBanana\nCherry";
  • Step 2: Collect Lines into a List
    The lines() method is used to split the string into lines, and the collect() method collects the stream of lines into a List<String>:
List<String> fruits = text.lines().collect(Collectors.toList());
  • Step 3: Display the List
    Finally, we print the list of lines (fruits):
System.out.println(fruits);

Key Points

  1. Line Terminators: The lines() method splits the string based on line terminators like \n (newline), \r\n (carriage return followed by newline), or \r (carriage return).
  2. Stream API: The lines() method returns a Stream<String>, making it compatible with Stream API operations like filter(), map(), collect(), and more.
  3. Empty Lines: If there are consecutive line terminators, the lines() method will treat that as an empty line.
  4. Use Cases: You can use lines() to read and process multiline strings, count lines, filter lines based on conditions, and collect lines into collections like lists.

Conclusion

The lines() method in Java 11 provides a convenient way to split strings into individual lines and process them using the Stream API. Whether you're filtering lines, counting lines, or transforming the data, the lines() method simplifies text processing, making your code cleaner and more efficient. It also integrates seamlessly with other Stream API operations, giving you flexibility when handling multi-line strings.

Comments