Reputation: 1
I found here a good code that will help me to finish a thing to do. But what I need: I have two lists, one list is example1.txt and sencond list is example2.txt I need to get similar and different. I dont know where to set the c://example1.txt and c://example2.txt
for example: Arrays.asList(c://example1.txt);
import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;
class Repeated {
public static void main( String [] args ) {
Collection<String> listOne = Arrays.asList("1","2","3");
Collection<String> listTwo = Arrays.asList("1","2","2");
Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );
similar.retainAll( listTwo );
different.removeAll( similar );
System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
}
}
Upvotes: 0
Views: 1471
Reputation: 533500
Sounds like homework, but I will bite. I would use FileUtils
Set<String> example1 = new LinkedHashSet<String>(
FileUtils.readLines(new File(args[0])));
Set<String> example2 = new LinkedHashSet<String>(
FileUtils.readLines(new File(args[1])));
Set<String> same = new LinkedHashSet<String>(example1);
same.retainAll(example2);
Set<String> different = new LinkedHashSet<String>(example1);
different.removeAll(example2);
if you have one ,
between values you can use
Set<String> example1 = new LinkedHashSet<String>(
Arrays.asList(FileUtils.readFileToString(new File(args[0])).split("[,\\s]")));
Upvotes: 2
Reputation: 597076
As far as I understand, you don't know how to read the text files to lists. There are many options:
IOUtils.readLines(new FileInputStream("c:/example.txt"))
new BufferedInputStream(new FileInputStream(..))
and then loop using the readLine()
methodTo handle encoding properly you will need to use new InputStreamReader(inputStream, "utf-8")
Update:
It seems your file contains only one line. Using the FileUtils
that Peter reminded me of:
String str = FileUtils.readFileToString("c:/filename.txt");
String[] numbers = str.split(",");
List<String> list = Arrays.asList(numbers);
Upvotes: 4