here I'm using a hashset to store seen lines
Scanner scan;//input Set<String> lines = new HashSet<String>(); StringBuilder strb = new StringBuilder(); while(scan.hasNextLine()){ String line = scan.nextLine(); if(!lines.contains(line)){ lines.add(line); strb.append(line); } }