I have an ArrayList
with values taken from a file (many lines, this is just an extract):
20/03/2013 23:31:46 6870 6810 6800 6720 6860 6670 6700 6650 6750 6830 34864 34272 20/03/2013 23:31:46 6910 6780 6800 6720 6860 6680 6620 6690 6760 6790 35072 34496
Where the first two values per line are strings that contain data and are stored in a single element.
What I want to do is compare the string data elements and delete, for example, the second one and all the elements referred to in that line.
For now, I've used a for
loop that compares the string every 13 elements (in order to compare only data strings).
My question: can I implement other better solutions?
This is my code:
import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) throws Exception{ //The input file Scanner s = new Scanner(new File("prova.txt")); //Saving each element of the input file in an arraylist ArrayList<String> list = new ArrayList<String>(); while (s.hasNext()){ list.add(s.next()); } s.close(); //Arraylist to save modified values ArrayList<String> ds = new ArrayList<String>(); // int i; for(i=0; i<=list.size()-13; i=i+14){ //combining the first to values to obtain data String str = list.get(i)+" "+list.get(i+1); ds.add(str); //add all the other values to arraylist ds int j; for(j=2; j<14; j++){ ds.add(list.get(i+j)); } //comparing data values int k; for(k=0; k<=ds.size()-12; k=k+13){ ds.get(k); //first data string element //Comparing with other strings and delete //TODO } } } }
Try checking for duplicates with a .contains()
method on the ArrayList, before adding a new element.
It would look something like this
if(!list.contains(data)) list.add(data);
That should prevent duplicates in the list, as well as not mess up the order of elements, like people seem to look for.
Create an Arraylist of unique values
You could use Set.toArray()
method.
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
http://docs.oracle.com/javase/6/docs/api/java/util/Set.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With