ErkanMDR
ErkanMDR

Reputation: 5

Delete duplicate lines from a String in Java

My string is:

"EEE
EEE
AAA
BBB
CCC
BBB
DDD
CCC"

But I need to without same lines this string. Like this:

"EEE
AAA
BBB
CCC
DDD"

How can I do it?

Upvotes: 0

Views: 3251

Answers (4)

Daniel
Daniel

Reputation: 4549

Here's a simple answer

StringBuilder builder = new StringBuilder(); 
for (String line: new LinkedHashSet<String>(Arrays.asList(inputString.split("\n"))) ) {
    builder.append(line).append("\n");
}
String result = builder.toString();

Upvotes: 2

user1830702
user1830702

Reputation: 1

Use Scanner like a StringBuffer, and LinkedHashset for search duplicate lines.

    String text = "Eds\r\nIsa\r\nEds\nIsa\r\nEds\nIsa";
    StringBuilder textResult = new StringBuilder();
    Set list = new LinkedHashSet<String>();
    Scanner scanner = new Scanner(text);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if(!list.contains(line)){
            list.add(line);
            textResult.append(line).append(System.getProperty("line.separator"));
        }
    }
    scanner.close();
    System.out.println(textResult);

Upvotes: 0

David Smith
David Smith

Reputation: 61

A suitable approach would be to use a set. This will allow you to filter a collection of strings and exclude repeated values. For example:

import java.util.*;

class Sorter
{
    public static void main(String[] args)
    {
        // The input string, this example uses groups of comma separated values
        String input = "EEE,EEE,AAA,BBB,CCC,BBB,DDD,CCC";

        // Create a new set, this will be used for filtering
        Set<String> set = new HashSet<String>();

        // Add each string within input, add to set.
        // Repeated values will be
        for (String s: input.split(","))set.add(s);

        // Format results
        for (String s: set) System.out.println(s);
    }
}

Upvotes: 0

Tregoreg
Tregoreg

Reputation: 22256

Considering you string being stored in String s, how about

String[] tokens = s.split("\n");
StringBuilder resultBuilder = new StringBuilder();
Set<String> alreadyPresent = new HashSet<String>();

boolean first = true;
for(String token : tokens) {

    if(!alreadyPresent.contains(token)) {
        if(first) first = false;
        else resultBuilder.append("\n");

        if(!alreadyPresent.contains(token))
            resultBuilder.append(token);
    }

    alreadyPresent.add(token);
}
String result = resultBuilder.toString();

or:

Set<String> tokens = new HashSet<String>(Arrays.asList(s.split("\n")));
StringBuilder resultBuilder = new StringBuilder();

boolean first = true;
for(String token : tokens) {
    if(first) first = false;
    else resultBuilder.append("\n")

    resultBuilder.append(token);
}

String result = resultBuilder.toString();

Upvotes: 1

Related Questions