Java HashMap Sepator and Fields - java

I want use Separtor and different fields in hashmap, I am trying to write program to find duplicate firstname and lastname fields in data than add sequction number,
Check firstname && lastname in all records
if firstname && lastname found duplicate add seqNumber in feilds like 0,1,2,3..
if didn't find duplicate than 0
I write the code is working fine.. but, it checking line.. instead of fields, I need to check 2 fields firstname and lastname..
Please help me!!
here is inputdata file:- I have data file like:
CustmerNumber,FirstName,LastName,Address1,city
123456789,abcd,efgh,12 spring st,atlanta
2345678,xyz,lastname,16 sprint st,atlanta
232345678,abcd,efgh ,1201 sprint st,atlanta
1234678,xyz,lastname,1234 oakbrook pkwy,atlanta
23556,abcd,efgh,3201 sprint st,atlanta
34564,robert,parker,12032 oakbrrok,atlanta
I want output data file like:
CustmerNumber,FirstName,LastName,Address1,city,**SEQNUMBER**
123456789,**abcd,efgh**,12 spring st,atlanta,**0**
232345678,**abcd,efgh** ,1201 sprint st,atlanta,**1**
23556,**abcd,efgh**,3201 sprint st,atlanta,**2**
2345678,**xyz,lastname**,16 sprint st,atlanta,**0**
1234678,**xyz,lastname**,1234 oakbrook pkwy,atlanta,**1**
34564,**robert,parker**,12032 oakbrrok,atlanta,**0**
Here is my Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class test1 {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Map<String, Integer> names = new HashMap<>();
File dir = new File("Data_File_In");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
s.nextLine();
while(s.hasNextLine()) {
String line = s.nextLine();
if(!names.containsKey(line)) {
names.put(line, 0);
}
names.put(line, names.get(line) + 1);
}
for(String name : names.keySet()) {
for(int i = 1; i <= names.get(name); i++) {
System.out.println(name + "---->" + (i-1));
}
}
s.close();
}
}
}
My Code is checking line if line is duplicate than sequction number is 0,1,2....
if not same like again than only 0
Instead of that need to use fields firstname and lastname..
Please help me!!
Thanks!!

Parse your line so you know the values of firstName and lastName
for each line. Then for each line use e.g. firstName + "###" + lastName
as the key of your map. The values in your map will be e.g. Integer values
(these are the counts). When reading a line, construct its key and see if it
is in the map already. If yes - increase the value i.e. the count, otherwise
add new entry in the map with count=1.

Related

Searching data from arraylist

I am a newbie of c++.
Now I am doing a project need to read a customer list from a csv file and then search if there is a username like "Ali" and printout all the data about Ali.
How can I search "Ali" and printout all the data about Ali like CustomerNo , Name , PhoneNo and Status?
And if there is multiple data with "Ali" , how can I printout all of them either?
Here is my code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Iterator;
public class LoadCustomer {
public static void main(String[] args) throws IOException{
System.out.println ("Load customer from file");
ArrayList<Customer> customers = readCustomerFromFile();
System.out.println (customers);
System.out.println ();
private static ArrayList<Customer> readCustomerFromFile() throws IOException{
ArrayList<Customer> customers = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("customer.csv"));
for (int i = 1 ; i < lines.size() ; i++){
String[] items = lines.get(i).split(",");
int customerNo = Integer.parseInt(items[0]);
int phoneNo = Integer.parseInt(items[2]);
customers.add (new Customer(customerNo,items[1],phoneNo,items[3]));
}
return customers;
}
}
Here is my Customer class:(added getName getter)
public class Customer {
private int customerNo;
private String name;
private int phoneNo;
private String status;
public Customer () {}
public Customer (int customerNo, String name, int phoneNo, String status){
this.customerNo = customerNo;
this.name = name;
this.phoneNo = phoneNo;
this.status = status;
}
public String getName(){
return name;
}
public String toString(){
return customerNo + " " + name + " " + phoneNo + " " + status;
}
public String toCSVString(){
return customerNo + "," + name + "," + phoneNo + "," + status;
}
}
And here is my data:
CustomerNo Name PhoneNo Status
1 Ali 12345 Normal
2 Siti 23456 Normal
3 Rone 78910 Normal
4 Jean 56789 Normal
5 Roby 28573 Normal
6 Ali 78532 Normal
Thank you very much for your attention.
Edited :
Here is my code for this program:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class FindCustomer {
public static void main(String[] args) throws IOException{
System.out.println ("Load customer from file");
java.util.Map<String, List<Customer>> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split(","))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors
.groupingBy(Customer::getName));
System.out.println (customers);
}
}
Bit of a broad question.
If you expect to do this a lot, and on a boatload of data, do what everybody else does when they are faced with a lot of relational data that they need to run queries on. Use a database, like postgres or h2. To interact with those from java, use JDBI or JOOQ.
If this is just a small simple text file and/or you're trying to learn some java, well, you still have two options here: You can loop through the data, or, you can build a mapping.
The loop option is simple:
for (Customer c : customers) if (c.getName().equals("Ali")) {
// do what you want here. 'c' holds the customer object of Ali.
}
But this does, of course, require a full run through all the entries every time. Another option is to build a mapping:
var map = new HashMap<String, Customer>();
for (Customer c : customers) map.put(c.getName(), c);
// map now maps a customer name to the customer object.
Customer ali = map.get("Ali");
maps have the advantage that they are near instant lookup. Even if the map contains a million entries, map.get(x) is (near) instant. A decent solution if you have lots of data + the need to do lots of lookups. But, you have to build a complete map for everything you care to query on. So, if you want to do lookups on name, and then later something like 'get all customers with a 6 digit phone number whose status is Normal', then, get a database.
As was suggested a map would be useful. You can create one on the fly as you read in the file.
Splits the line
creates a customer.
and groups it by name in a map.
Now the map will hold for each name, all customers that have that name.
Map<String, List<Customer>> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split("\\s*,\\s*"))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors
.groupingBy(Customer::getName));
To get the List of customers for the name Ali do the following.
List<Customer> ali = customers.get("Ali");
Now it's up to you to format or otherwise use the list as required. You will still need to handle exceptions via try/catch.

validate ArrayList contents against specific set of data

I want to check and verify that all of the contents in the ArrayList are similar to the value of a String variable. If any of the value is not similar, the index number to be printed with an error message like (value at index 2 didn't match the value of expectedName variable).
After I run the code below, it will print all the three indexes with the error message, it will not print only the index number 1.
Please note that here I'm getting the data from CSV file, putting it into arraylist and then validating it against the expected data in String variable.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class ValidateVideoDuration {
private static final String CSV_FILE_PATH = "C:\\Users\\videologs.csv";
public static void main(String[] args) throws IOException {
String expectedVideo1Duration = "00:00:30";
String expectedVideo2Duration = "00:00:10";
String expectedVideo3Duration = "00:00:16";
String actualVideo1Duration = "";
String actualVideo2Duration = "";
String actualVideo3Duration = "";
ArrayList<String> actualVideo1DurationList = new ArrayList<String>();
ArrayList<String> actualVideo2DurationList = new ArrayList<String>();
ArrayList<String> actualVideo3DurationList = new ArrayList<String>();
try (Reader reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH));
CSVParser csvParser = new CSVParser(reader,
CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) {
for (CSVRecord csvRecord : csvParser) {
// Accessing values by Header names
actualVideo1Duration = csvRecord.get("Video 1 Duration");
actualVideo1DurationList.add(actualVideo1Duration);
actualVideo2Duration = csvRecord.get("Video 2 Duration");
actualVideo2DurationList.add(actualVideo2Duration);
actualVideo3Duration = csvRecord.get("Video 3 Duration");
actualVideo3DurationList.add(actualVideo3Duration);
}
}
for (int i = 0; i < actualVideo2DurationList.size(); i++) {
if (actualVideo2DurationList.get(i) != expectedVideo2Duration) {
System.out.println("Duration of Video 1 at index number " + Integer.toString(i)
+ " didn't match the expected duration");
}
}
The data inside my CSV file look like the following:
video 1 duration, video 2 duration, video 3 duration
00:00:30, 00:00:10, 00:00:16
00:00:30, 00:00:15, 00:00:15
00:00:25, 00:00:10, 00:00:16
Don't use == or != for string compare. == checks the referential equality of two Strings and not the equality of the values. Use the .equals() method instead.
Change your if condition to if (!actualVideo2DurationList.get(i).equals(expectedVideo2Duration))

How to read multiple csv files with different formats in java [duplicate]

This question already has answers here:
how to read csv file without knowing header using java?
(3 answers)
Closed 6 years ago.
I am implementing csv file listener using watchservice. My requirement is :
Get csv files from the registered directory with java watch service. I am struggling to process the received files and stored data into the database. the problem here is - CSV file format is not predefined, file can have any number of columns and different headers. I have referred many sites but not found any solution. please help.
this sample code helps you to process your files:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
private static String HEADER_DELIMITER = ",";
private static String DATA_DELIMITER = ",";
public static void main(String[] args) {
/**
* for each file read lines and then ...
*/
String headerLine = "id,name,family";
String[] otherLines = { "1,A,B", "2,C,D" };
List<Student> students = new ArrayList<Student>();
String[] titles = headerLine.split(HEADER_DELIMITER);
for (String line : otherLines) {
String[] cells = line.split(DATA_DELIMITER);
Student student = new Student();
int i = 0;
for (String cell : cells) {
student.add(titles[i], cell);
i++;
}
students.add(student);
}
System.out.println(students);
/*
* output:
* [Student [data={id=1, family=B, name=A}], Student [data={id=2, family=D, name=C}]]
*/
/**
* save students in your table.
*/
}
static class Student {
Map<String, String> data = new HashMap<String, String>();
public void add(String key, String value) {
data.put(key, value);
}
#Override
public String toString() {
return "Student [data=" + data + "]";
}
}
}
for saving the result in your data base, it depends on your decision about your data model. for example if these csv files are common in most columns and are different in a few columns I suggest this data model:
you should have a table (for example Student) with common columns (id, name, family) and another table with only 3 columns (studentForeignKey, key, value) and store other extra columns in this table. for example (id=1, key=activity, value=TA) and it means that the student with id = 1 has TA activity.
I hope this answer could help you

If state rework, ignore-case clarification

So, I have a class that creates a Song object containing a Title: Artist: Album.
I prompt the user to ask for a particular artist, and from an ArrayList containing a master play list, the program returns a list, sorted by Title, for each particular artist. This was no problem. The issue I am having is at the point where the user asks for an artist that is not in the master play list. When I code this using an if/then/else, I am receiving one Sysout for every case in which the prompted artist does not match an artist in the master play list. Also, when the user inputs a proper artist, the correct, formatted Arraylist is generated, along with the Sysout for every artist that didn't match the prompted name (so, the entire master list essentially). I need to EITHER return a formatted ArrayList containing only the artist prompted, or a single statement, such as, "Artist not found in list." I've been stuck for a couple of hours, and need a couple of fresh minds on this, if you will. I know why it is happening, I just can't figure my way around my intended output. Also, a little help in understanding why ignoreCase() is not working for me (for checking the searchArtist against an instance variable of Song object) would a big help.
Below is the current code:
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class SongList {
public static void main(String[] args){
//An arraylist theList to accept a file containg title : artist : album
ArrayList<Song> theList = new ArrayList<Song>();
try{
Scanner in = new Scanner(System.in);
File inputFile;
// Prompts user for proper input
do{ System.out.println("Please enter a valid input file.");
String input = in.next();
inputFile = new File(input);
}while(!inputFile.exists());
Scanner inp = new Scanner(new FileReader(inputFile));
String line = "";
//Accepts a line that is greater in length that 2 (it assumes a colon, and one blank space)
while((inp.hasNextLine()))
{
line = inp.nextLine();
line = line.trim();
if(line.length() > 2){
Song n = createSong(line);
theList.add(n);
}
}
}
catch(Exception e){
System.out.println("Error with the input file: " + e.getMessage());
}
Collections.sort(theList); //Sorts by title
//An arrayList particularArtist that creates an arrayList of a specified artist as given by the user
ArrayList<Song> particularArtist = new ArrayList<Song>();
Scanner sa = new Scanner(System.in);
String searchArtist = "";
System.out.print("Please enter the name of an artist you'd like to find.");
searchArtist = sa.next();
//This is where I am having the issue.
for(Song theArtist : theList)
if(theArtist.getArtist().contains(searchArtist))
{
particularArtist.add(theArtist);
}
else{System.out.println("The artist you are looking for does not exist in the play list.");}
for(Song is : particularArtist)
System.out.println(is);
}
/*
* Method for creating a Song object given an input file. In the format "Title : Artist: Album," substrings
* are created at the colons, and white space is trimmed.
*/
public static Song createSong(String a) {
int index1 = a.indexOf(':');
int index2 = a.indexOf(':', index1 + 1);
Song s = new Song(a.substring(0, index1).trim(), a.substring(index1 + 1, index2).trim(), a.substring(index2 + 1).trim());
return s;
}
}
solution: if the match exists then add to the result list (particularArtist). If the result list is empty then print artist doesn't exist.
for(Song theArtist : theList) {
if(theArtist.getArtist().contains(searchArtist)) {
particularArtist.add(theArtist);
}
}
for(Song is : particularArtist) {
System.out.println(is);
}
if (particularArtist.size() == 0) {
System.out.println("The artist you are looking for does not exist in the play list.")
}

How to convert CSV string to integer and add it. store ing txtfile

can you help me to this, I wanted to add 2 integer coming from CSV and store it in txtfile, but the problem is it was string and if i convert it to an integer i've gots lots of error.. Thank you guys..
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
public static void main (String[]arg)throws Exception {
String readFile = "C:/Users/user/Desktop/student.csv";
String writeFile = "C:/Users/user/Desktop/data.txt";
// Read a comma-separated values (CSV) file.
BufferedReader CSVFile = new BufferedReader (new FileReader(readFile));
// Read line.
String dataRow = CSVFile.readLine();
// Create an array of student
List<Student> students = new ArrayList <Student> ();
// The while checks to see if the data is null. If
// it is, we’ve hit the end of the file. If not,
// process the data.
while (dataRow !=null){
String [] dataArray = dataRow.split(",");
System.out.println(dataRow);
Student student = new Student();
student.setStudentName(dataArray[0]);
student.setScore1(dataArray[1]);
student.setScore2(dataArray[2]);
students.add(student);
dataRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
StringBuilder sb = new StringBuilder();
FileWriter fw = new FileWriter(writeFile);
for (Student s : students){
sb.append(s.studentName);
System.out.println(s.studentName + " - " + (s.score1 + s.score2));
// Writing to a text file.
fw.write(sb.toString());
}
// Close the file once all data has been written.
fw.close();
}
}
output:
che,cheche,chet
100,100,100
100,100,100
null - 0
null - 0
null - 0
it should br:
che,cheche,chet
100,100,100
100,100,100
che - 200
cheche -200
chet - 200
If the info you have provided is correct, then the main issue you have is the CSV data is in a columnar format, rather than a typical row format. By that, I mean the first row is name, with the next rows the scores. Each "column" of data matches up with the "header" at the same index.
Your example data:
che, cheche, chet -- row[0]
100, 100, 100 -- row[1]
100, 100, 100 -- row[2]
So row[0] is the name, but you are parsing te data as if the 1st item of a row is the name, and the 2nd and 3rd items are scores - which is not the case based on this sample data.
If you wanted scores you'd need to get the proper index for each row - so che would be row[1][0] and row[2][0].
If this is in fact the case, then you'll want to process the first row to get the names, then you'll want to process the remaining rows to get the scores.
You can try
int number = Integer.parseInt("your string here");
Example:
String one = "1";
String two = "2";
System.out.println(Integer.parseInt(one) + Integer.parseInt(two));
You have made few mistakes in the code.
The score variables in the student class should be integer.
To convert a string to Integer you need to use Integer.parseInt
method. Ideally your conversion should be at the stage when you are
setting the score values.
Why are you adding student object to an ArrayList. Can't you
directly write to the text file?

Categories

Resources