parsing - How to check for duplicate records in .csv using java -
i have csv file:
10;name1;id1 20;name2;id2 10;name3;id3
row row push data method called forward:
forward(nr, name, id);
how can check whole csv if "nr" duplicate? in above example is: 10.
my code now:
while ((line = reader.readline()) != null) { scanner = new scanner(line); scanner.usedelimiter(";"); while (scanner.hasnext()) { string data = scanner.next(); if (index == 0) nr = integer.parseint(data); else if (index == 1) name = data; else if (index == 2) id = data; else system.out.println("invalid data::" + data); index++; } index = 0; forward(nr, name, id); }
if duplicate found, want print on screen.
use map<long, string>
. each time before forward output can check if map contains key (the number) already.
map<long, string> entrymap = new hashmap<long, string>(); [...] if (!entrymap.containskey(nr)) { entrymap.put(nr, name); forward(nr, name, id); } else system.out.println("entry number " + nr + " added .csv file");
if number relevant , don't need put exceptions (e.g., entry name , number in file
), might want choose other data structures, e.g., list
.
as read in comments above, if replacing intention following:
create class keeps parameters:
public class csventry { private int number; private string name, id; public csventry(number, name, id) { this.number = number; this.name = name; this.id = id; } // getters & setters }
and change map
to:
map<long, csventry> entrymap = new treemap<long, csventry>(); // treemap entries sorted. [...] entrymap.put(nr, new csventry(nr, name, id)); // after populating map, e.g., after outer loop forward(entrymap);
and in forward loop map output.
Comments
Post a Comment