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?
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();