Sorting a CSV file by district - java

Hello I wanna create a program that sorts the following csv file I'm trying to sort the file by their district. So the following program reads the file and is able to sort it but it sorts it by their name and I wanna change it so it sorts by district any help is appreciated.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortDistrict
{
private static final String COLUMN_SEPARATOR = ",";
public static void main(String[] args) throws Exception
{
InputStream inputStream = new FileInputStream("data.csv");
List<List<String>> lines = readCsv(inputStream);
// Create a comparator that compares the elements from column 0,
// in ascending order
Comparator<List<String>> c0 = createAscendingComparator(0);
// Create a comparator that compares the elements from column 2,
// in descending order
Comparator<List<String>> c1 = createDesendingComparator(2);
// Create a comparator that compares primarily by using c0,
// and secondarily by using c1
Comparator<List<String>> comparator = createComparator(c0, c1);
Collections.sort(lines, comparator);
OutputStream outputStream = new FileOutputStream("output.csv");
String header = "Last Name, First Name, Email, Address, Age, District, Gender";
writeCsv(header, lines, outputStream);
}
private static List<List<String>> readCsv(
InputStream inputStream) throws IOException
{
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
List<List<String>> lines = new ArrayList<>();
String line = null;
// Skip header
line = reader.readLine();
while (true)
{
line = reader.readLine();
if (line == null)
{
break;
}
List<String> list = Arrays.asList(line.split(COLUMN_SEPARATOR));
lines.add(list);
}
return lines;
}
private static void writeCsv(
String header, List<List<String>> lines, OutputStream outputStream)
throws IOException
{
Writer writer = new OutputStreamWriter(outputStream);
writer.write(header+"\n");
for (List<String> list : lines)
{
for (int i = 0; i < list.size(); i++)
{
writer.write(list.get(i));
if (i < list.size() - 1)
{
writer.write(COLUMN_SEPARATOR);
}
}
writer.write("\n");
}
writer.close();
}
#SafeVarargs
private static <T> Comparator<T>
createComparator(Comparator<? super T>... districts)
{
return (t0, t1) ->
{
for (Comparator<? super T> district : districts)
{
int n = district.compare(t0, t1);
if (n != 0)
{
return n;
}
}
return 0;
};
}
private static <T extends Comparable<? super T>> Comparator<List<T>>
createAscendingComparator(int index)
{
return createListAtIndexComparator(Comparator.naturalOrder(), index);
}
private static <T extends Comparable<? super T>> Comparator<List<T>>
createDesendingComparator(int index)
{
return createListAtIndexComparator(Comparator.reverseOrder(), index);
}
private static <T> Comparator<List<T>>
createListAtIndexComparator(Comparator<? super T> delegate, int index)
{
return (list0, list1) ->
delegate.compare(list0.get(index), list1.get(index));
}
}
I also have a Person class if it'll be any use
public class Person implements Comparable<Person> {
private String name;
private String email;
private String address;
private String residency;
private String gender;
private int age;
private int district;
public Person(String name, String email, String address, String gender, String residency, int district, int age) {
this.name = name;
this.address = address;
this.age = age;
this.district = district;
this.residency = residency;
this.gender = gender;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getAge() {
return age;
}
public String getResidency() {
return residency;
}
public int getDistrict() {
return district;
}
public String getGender() {
return gender;
}
public String toString() {
return (name + "," + email + "," + address + "," + age + "," + residency + "," + district + "," + gender);
}
public int compareTo(Person another) {
if (district == another.getDistrict())
return 0;
else if (district < another.getDistrict())
return -1;
else
return 1;
} // end of compareTo
} // end of Person
The csv file is quite big but here is a few lines
First Name, Last Name, Email, Address, Age, Residency, District, Gender
Colleen,Joyner,commodo.auctor#elementumat.net,Ap #697-1279 Nullam Road,30,Resident,4,Female
Fay,Parker,augue.ut.lacus#egetvarius.edu,"P.O. Box 234, 6576 Et, Ave",24,Resident,4,Female
TaShya,Atkinson,sem.egestas#urna.com,"6319 At, St.",45,Resident,15,Female
Curran,Shannon,massa#arcu.com,"980 In, Rd.",57,Resident,8,Male
Yolanda,Snyder,ipsum.ac#Sednullaante.org,"P.O. Box 769, 8207 Egestas Avenue",54,Non-Resident,4,Female
Candice,Weaver,ligula#Aenean.ca,"Ap #599-9287 Tellus, Rd.",35,Resident,9,Female
Yoshio,Silva,fames#Cumsociisnatoque.co.uk,Ap #327-6404 Dui St.,19,Resident,4,Male
Thanks in advance

You need to sort a large CSV file by a specific field and output result to another CSV file. The code will be complex and lengthy if you try to do this in Java.
Yet, with SPL, the open-source Java package, you only need one line of code:
A
1
>file("output.csv").export#ct(file("data.csv").cursor#cqt().sortx(District))
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as sort.splx and invoke it in Java as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st=con.prepareCall("call sortx()");
st.execute();
…
Or execute the SPL string within a Java program as we execute a SQL statement:
…
st = con.prepareStatement("=>file(\"output.csv\").export#ct(file(\"data.csv\").cursor#cqt().sortx(District))");
st.execute();
…

Related

generating groups from txt file and generating them based on preferences

I am designing a group generator that takes in preferences such as “mix gender”, “mix nationality”... I am putting a list of student names, followed by nationality and gene set, in an arraylist. What is the easiest way to generate groups, based on user input, that each group consists of people from different nationalities, or balanced gender.
public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;
}
I am using this to read a text file, and on each line, I have each student's name nationality and gender. I put them into an ArrayList and am right now trying to figure out how to evenly distribute them based on the user-desired group numbers.
I am using a txt file to store all the information since this group generator is customized for my school.
You can use the groupinBy method
basic tutorial
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
String student1 = "Macie American Female";
String student2 = "Yago Brazilian Male";
String student3 = "Tom American Male";
List<String> students = Arrays.asList(student1, student2, student3);
System.out.println(groupByGender(students));
System.out.println(groupByNationality(students));
}
private static Map<String, List<Student>> groupByNationality(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getNationality));
}
private static Map<String, List<Student>> groupByGender(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getGender));
}
private static Student mapToStudent(String s) {
String[] ss = s.split(" ");
Student student = new Student();
student.setName(ss[0]);
student.setNationality(ss[1]);
student.setGender(ss[2]);
return student;
}
private static class Student {
String name;
String nationality;
String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", nationality='" + nationality + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
}
First of all, it would be better if you put your while loop inside the try block because you don't want to get there if the file hasn't been found.
Second, you don't need to create a new instance of Scanner just to read every line. You can simply read your file word by word:
while (sc2.hasNext())
readword.add(sc2.next());
To group the students according to their nationality, you can do something like that:
String nationality = [UserInput] ;
List<String> group = new ArrayList<>();
for (int i = 0; i < readword.size(); i++)
if (readword.get(i + 1).equals(nationality)
group.add(readword.get(i));

JSoup HTML Parse and Write Results to CSV In Order

I am trying to find the best approach to saving the data I have parsed out of the HTML document when Jsoup into a CSV. The problem I'm having is using [CSVWriter][1] - https://mvnrepository.com/artifact/com.opencsv/opencsv/4.6 and writing the data with it. Please see my code snippet below. The structure of the data looks like the following with infobox being the main listing record with each subsequent field within it. The CSVWriter looks like it is a String Array but having trouble going from elements to write to the CSVData writer with a String Array.
The Jsoup selector is returning an array of items from the selection. For instance, when I make the selection for the name, it is returning all 9 names if there are 9 records on the page. I need to put this data together in order for each row to print into a CSV.
InfoBox >
Name|
Email|
Phone|
Website
The problem I'm having is how I'm trying to write the data on this line below
writer.writeAll((Iterable<String[]>) infoArray);
This is not working correctly and errors but wanted to show what I am kind of after and if there is somebody who's familiar with writing data from Jsoup Elements into CSV. Thanks
String filePath ="c:/results.csv";
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
String[] header = { "Name", "Phone", "Street","State","City","Zipcode" };
Elements infobox = doc.select(".info");
List<String> infoArray = new ArrayList<>();
for(int i = 0; i < infobox.size(); i++){
infobox.get(i).select(".business-name > span");
infoArray.add(infobox.get(i).select(".business-name > span").text());
infoArray.add(infobox.get(i).select(".phones.phone.primary").text());
infoArray.add(infobox.get(i).select(".street-address").text());
infoArray.add(infobox.get(i).select(".state").text());
infoArray.add(infobox.get(i).select(".city").text());
infoArray.add(infobox.get(i).select(".zip").text());
}
writer.writeNext(header);
//How to write data in order to match each record accordingly?
//Data should be written to CSV like the following example under each header into each corrosponding row
//name, phone, street
writer.writeAll((Iterable<String[]>) infoArray);
for(String ia : infoArray){
}
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here's what ended up working for me. The problem was not adding Strings into a String array to pass to CSVWriter. Here is my example.
try {
String[] header = { "Name", "Phone", "Street","State","City","Zipcode" };
Elements infobox = doc.select(".info");
if(count == 0){
writer.writeNext(header);
}
for(int i = 0; i < infobox.size(); i++){
infobox.get(i).select(".business-name > span");
String businessName = infobox.get(i).select(".business-name > span").text();
String phone = infobox.get(i).select(".phones.phone.primary").text();
String address = infobox.get(i).select(".street-address").text();
//Address seems to be displayed another way too
String address2 = infobox.get(i).select(".adr").text();
//Use regular expression to normalize data
String[] columns = new String[]{
businessName, phone, address
};
writer.writeNext(columns);
}
writer.close();
}
Here is little example how to use OpenCSV. Maybe will be helpful for you.
HeaderNames.java
public class HeaderNames
{
public static final String NAME = "Name";
public static final String PHONE = "Phone";
public static final String STREET = "Street";
public static final String STATE = "State";
public static final String CITY = "City";
public static final String ZIPCODE = "Zipcode";
}
DemoDTO.java
import java.io.Serializable;
import com.opencsv.bean.CsvBindByName;
public class DemoDTO implements Serializable
{
private static final long serialVersionUID = 1L;
#CsvBindByName(column = HeaderNames.NAME)
private String name;
#CsvBindByName(column = HeaderNames.PHONE)
private String phone;
#CsvBindByName(column = HeaderNames.STREET)
private String street;
#CsvBindByName(column = HeaderNames.STATE)
private String state;
#CsvBindByName(column = HeaderNames.CITY)
private String city;
#CsvBindByName(column = HeaderNames.ZIPCODE)
private String zipcode;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getZipcode()
{
return zipcode;
}
public void setZipcode(String zipcode)
{
this.zipcode = zipcode;
}
}
Main.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVWriter;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
public class Main
{
public static void main(String[] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException
{
File file = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "results.csv");
FileWriter writer = new FileWriter(file);
List<DemoDTO> beans = new ArrayList<DemoDTO>();
for (int i = 0; i < 10; i++)
{
DemoDTO demoDTO = new DemoDTO();
demoDTO.setCity("city " + i);
demoDTO.setName("name " + i);
demoDTO.setPhone("phone " + i);
demoDTO.setState("state " + i);
demoDTO.setStreet("street " + i);
demoDTO.setZipcode("zipcode " + i);
beans.add(demoDTO);
}
HeaderColumnNameMappingStrategy<DemoDTO> strategy = new HeaderColumnNameMappingStrategy<>();
strategy.setType(DemoDTO.class);
StatefulBeanToCsv<DemoDTO> beanToCsv = new StatefulBeanToCsvBuilder<DemoDTO>(writer)
.withSeparator(';')
.withEscapechar(CSVWriter.NO_ESCAPE_CHARACTER)
.withLineEnd(CSVWriter.DEFAULT_LINE_END)
.withQuotechar(CSVWriter.DEFAULT_QUOTE_CHARACTER)
.withMappingStrategy(strategy)
.withThrowExceptions(true)
.build();
beanToCsv.write(beans);
writer.flush();
writer.close();
}
}

How to read a file containing strings and integers into an ArrayList and sort by integer?

I'm trying to read from a text file containing a list of names and grades, organized by line, i.e.:
David Smith 84
Susan L Potter 100
...
Then store them (by line) in an ArrayList, and sort that ArrayList by the students' grade using a selection sort algorithm, however I've tried multiple different ways to code this and every edit seems to prompt another error (I'm extremely new to programming). This is what I currently have:
import java.io.*;
import java.util.*;
public class Grades {
private static void sort(ArrayList<String> list) {
int pFill;
int pTest;
int pSmallest;
String temp;
for (pFill = 0; pFill < list.size(); pFill++) {
pSmallest = pFill;
for (pTest = pFill + 1; pTest < list.size(); pTest++) {
if (pTest < pSmallest) {
pSmallest = pTest;
}
}
temp = list.get(pSmallest);
list.set(pSmallest, list.get(pFill));
list.set(pFill, temp);
}
}
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
list.add(input.readLine());
}
input.close();
sort(list);
System.out.println(list);
} catch (IOException e){
System.out.println(e.getMessage());
}
}
}
You can create a student object to hold name and grade separately. Once you have added all the data into list you can directly use list.sort() method by using Comparator but in your case you want to write selection sort that's why you have to write another method to do selection sort.
package com.stackovflow.problems;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Grades {
public static void main(String[] args){
ArrayList<Student> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
String line = input.readLine().trim();
String name = line.substring(0,line.lastIndexOf(' '));
int grade = Integer.parseInt(line.substring(line.lastIndexOf(' ')+1));
list.add(new Student(name, grade));
}
input.close();
selectionSort(list);
System.out.println(list);
} catch (IOException e){
System.out.println(e.getMessage());
}
}
private static void selectionSort(ArrayList<Student> list) {
int pFill;
int pTest;
int pSmallest;
Student temp;
for (pFill = 0; pFill < list.size(); pFill++) {
pSmallest = pFill;
for (pTest = pFill + 1; pTest < list.size(); pTest++) {
Student pTestStudent = list.get(pTest);
Student pSmallestStudent = list.get(pSmallest);
if (pTestStudent.getGrade() < pSmallestStudent.getGrade()) {
pSmallest = pTest;
}
}
if(pSmallest!=pFill) {
temp = list.get(pSmallest);
list.set(pSmallest, list.get(pFill));
list.set(pFill, temp);
}
}
}
}
//This class is to hold line data in your students.txt file
class Student{
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Student(String name, int grade) {
super();
this.name = name;
this.grade = grade;
}
#Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
}
It will be easy if you declare a Student class with 2 fields name and age. And you can make the Student class implement Comparable and compare on the basis of grade. It will look something like this:
public class Student implements Comparable<Student> {
private final String name;
private final int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
#Override
public int compareTo(Student s) {
return Integer.compare(this.grade, grade);
}
}
To populate the Student object you will need to split the String and extract the name and grade, and then call new Student(name, grade).
In your sort method you can pass a List<Student> where you can compare 2 students (as Student implements Comparable<Student>) by calling something like s1.compareTo(s2).
Once you got the list of student. You can use Comparator to do this.
List<Student> sorted=list.sort(Comparator.comparing(p-> p.getGrade()));
Or use stream api
List<Person> result =list.stream().sorted((p1, p2)>p1.getGrade().compareTo(p2.getGrade())).collect(Collectors.toList());
Create a separate Student.java file in the same folder to hold the Student class:
public class Student {
private final String name;
private final int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName(){
return name;
}
public int getGrade(){
return grade;
}
}
Then split each line by space and set the first tokens as the name and the last as the grade, then use Comparator to sort the ArrayList of Student Objects:
import java.io.*;
import java.util.*;
public class Grades {
private static ArrayList<Student> sort(ArrayList<String> list) {
ArrayList<Student> students = new ArrayList<Student>();
String name = "";
int grade;
for (String line : list) {
String[] splitted = line.split("\\s+");
for(int i = 0;i< splitted.length-1;i++){
name += splitted[i] + " ";
}
grade = Integer.parseInt(splitted[splitted.length-1]);
students.add(new Student(name,grade));
name = "";
}
students.sort(Comparator.comparing(student-> student.getGrade()));
return students;
}
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
list.add(input.readLine());
}
input.close();
ArrayList<Student> sortedStudents = sort(list);
for (Student currentStudent : sortedStudents)
System.out.println(currentStudent.getName() + currentStudent.getGrade());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
}

What is Wrong with my Collections.sort?

I am working on my final for school, and am running into a bit of an issue.
I have created different sorts for the user to sort the information, but I have been getting different errors.
The main one being "The method sort(List, Comparator) in the type Collections is not applicable for the arguments (ApplicationList, ApplicationList.AgeComparator)".
I do not know what this means, or how to fix it.
The code is as follows:
ApplicationList.Java;
import java.util.*;
public class ApplicationList implements Comparable<ApplicationList>
{
/**
* variables within the queue class
*/
private int maxSize;
private String[] queArray;
private int front;
private int rear;
private int nItems;
/**
* This is the constructor
*/
public ApplicationList(int size) {
maxSize = size;
queArray = new String[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
/**
* Adds to the bottom of the queue, and determines if the queue is full
*/
public void enqueue(String j) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (rear == maxSize - 1)
rear = front - 1;
queArray[rear + 1]=j;
rear++;
nItems++;
}
}
/**
* dequeues items from the top of the queue
*/
public String dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
} else {
String j = queArray[front];
front++;
if (front == maxSize)
front = 0;
nItems--;
return j;
}
}
/**
* peeks at the front of the queue
*/
public String peekFront() {
return queArray[front];
}
/**
* determines if the queue is empty
*/
public boolean isEmpty() {
return (nItems == 0);
}
/**
* Determines if the queue is full
*/
public boolean isFull() {
return (nItems == maxSize);
}
/**
* determines size of queue
*/
public int size() {
return nItems;
}
public void display()
{
for (int i = 0; i< nItems; i++)
System.out.println(queArray[(front+i) % maxSize]);
System.out.println(" ");
}
private String lastName;
private String firstName;
private int age;
private String email;
private String education;
private String experience;
public ApplicationList(String lastName, String firstName, int age, String email, String education, String experience)
{
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
this.email = email;
this.education = education;
this.experience = experience;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String toString() {
return "Applicant: Last Name: " + lastName + " ||| " +"First Name: " + firstName +" ||| " + " Email: " + email +" ||| " + " Age: " + age +" ||| " +
" Education: " + education +" ||| " + " Experience: " + experience;
}
static List<String> definedOrder = Arrays.asList("4+ years","2 years","Diploma","GED","NA");
static Comparator<ApplicationList> EducationComparator= new Comparator<ApplicationList>() {
public int compare(ApplicationList e1, ApplicationList e2) {
return Integer.valueOf(definedOrder.indexOf(e1.getEducation())).compareTo(Integer.valueOf(e2.getEducation()));
}
};
static class AgeComparator implements Comparator<ApplicationList> {
public int compare(ApplicationList p1, ApplicationList p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public int compareTo(ApplicationList n) {
return getLastName().compareTo(n.getLastName());
}
}
Here is the driver, which is the one that is causing the problem:
ApplicationDriver.Java;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class ApplicationDriver
{
public static <T> void main(String[] args) throws IOException {
ApplicationList Applicants = new ApplicationList(5);
ApplicationList sSmith = new ApplicationList("Smith", "Steve", 34, "SSmith#work.email", "GED", "Did a review on other games, hoping to review yours as well." );
ApplicationList jRosen = new ApplicationList("Rosen", "Jane", 23, "RosenWall#zmail.com", "4+ years", "Game reviewing was somthing I've always wanted to try." );
ApplicationList hAbhul = new ApplicationList("Abhul", "Habib", 19, "SwimminIndian#LookIn.org", "NA", "I like playing games, and feel like I have good insight." );
ApplicationList aJones = new ApplicationList("Jones", "Abigail",27, "Jonsin4Love#zmail.com", "2 years", "I went to school for journalism, and think that I can write a fair and honest review of your games." );
ApplicationList gInsider = new ApplicationList("Insider", "Gaming",0, "Michael#G.Insider.com", "Diploma", "Hi there, I am Michael from Gaming Insider. I see you are an upcoming developer, and want to see what you can do." );
Applicants.enqueue(sSmith.toString());
Applicants.enqueue(jRosen.toString());
Applicants.enqueue(hAbhul.toString());
Applicants.enqueue(aJones.toString());
Applicants.enqueue(gInsider.toString());
boolean success;
while(true) {
System.out.print("Enter the first letter of ");
System.out.print("display, sort, remove: ");
int choice = getChar();
switch(choice) {
case 'd':
Applicants.display();
break;
case 's':
System.out.print("Enter the first letter to sort by ");
System.out.print("name, age, education: ");
int select = getChar();
case 'e':
Collections.sort(Applicants, ApplicationList.EducationComparator);
Applicants.display();
break;
case 'a':
Collections.sort(Applicants, new ApplicationList.AgeComparator());
Applicants.display();
break;
case 'n':
Collections.sort(Applicants);
Applicants.display();
break;
case 'r':
Applicants.dequeue();
Applicants.display();
break;
default:
System.out.println("Invalid Entry, retry\n");
}
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
The Collections.sort is where my problems lie. What do I do to go about fixing my issues? If you need any more information, please ask!
Thanks for any and all help you are willing to give, and I apologize if my formatting for the website is horrible, I tried my best with it.
Thank you again for the assistance!
Aaron
You are violating the Single Responsibility Principle.
ApplicationList seems to represent two things:
a list of applicants
an applicant
Those two ideas are very distinct. You should create a class for each of them. To represent a list of applicants, you have a class called ApplicationList, and to represent one individual applicant, make a class called Applicant. Move all the fields and methods related to the applicant to the Applicant class (the age, name, email etc, and the constructor taking these parameters...). And then you can change queArray's type to Applicant[].
Your Collection.sort does not work because ApplicationList does not implement Collection.
Now, you need to implement the Collection interface in order for the ApplicationList to be sorted with Collection.sort. The interface has quite a few methods but they should be easy to implement.
Alternatively, you can just call Arrays.sort and sort the queArray instead.

To print the content of object?

What changes should i perform in my code so that it could print the whole family
Have tried toString, i am only getting null. This is just a pretty simple code soo plss help.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Alpit on 26-05-2017.
*/
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
}
class add {
public static void main(String args[]) throws IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
String f = obj.readLine();
String s = obj.readLine();
String b = obj.readLine();
String m = obj.readLine();
Fam fam = new Fam(f, s, b, m);
arrayList.add(fam);
}
for (Object x : arrayList) {
System.out.println(String.valueOf(x));
}
}
}
I am only getting the address of Object, This question can be considered to be a duplicate of this question but i was not able to understand by the solution provided there.
This is what i tried again
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Alpit on 26-05-2017.
*/
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String toString()
{
return r;
}
}
class add {
public static void main(String args[]) throws IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
String f = obj.readLine();
String s = obj.readLine();
String b = obj.readLine();
String m = obj.readLine();
Fam fam = new Fam(f, s, b, m);
arrayList.add(fam);
}
for (Object x : arrayList) {
System.out.println(x.toString());
}
}
}
And this returns null.
You can override toString() from Object in your Class Fam.
What String.valueOf(object) does is that it calls the toString() method of class Object (in your case it is Fam).
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So you would need to override the toString() method in Fam class like this:
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
.
.
.
#Override
public String toString() {
return this.father +" "+this.mother +" "+ this.sister +" "+ this.brother;
}
Additionally, you will need to make this change in your main method.
ArrayList<Fam> arrayList = new ArrayList<Fam>();
This way you will get your object printed. (PS: you can change the return format in toString() method.)
Implement your own toString() method. Do something like this:
class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.father);
builder.append(" ");
builder.append(this.sister);
builder.append(" ");
builder.append(this.brother);
builder.append(" ");
builder.append(this.mother);
return builder.toString();
}
}
class add {
public static void main(String args[]) throws IOException {
Fam family = new Fam("father", "sister", "brother", "mother");
System.out.println(family.toString());
}
}
I have implmented toString() here. I have used a StringBuilder to demonstrate how you can create your own method, inserting a space between "father, sister, brother, mother".
Running you get:
father sister brother mother
Your ArrayList is given a type parameter of Object. This is fine and all, but when you're trying to print the data in the for loop, you'll need to cast x to Fam. It would be easier to declare it like ArrayList<Fam> arrayList = new ArrayList<>(). Also, you can't simply print objects the way you're trying to do it. Object references hold the value of the memory address. You'll need to manually print the data by using the getter methods in your Fam class. You could also override the toString() method to do this if you want.

Categories

Resources