I want to alphabetize objects by a variable defined in its class - java

I am making a program that sets up an experiment for me and I want to alphabetize the subjects (or people) that i input. I have an arraylist of type subjects and i want to alphabetize them by their names.
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Experiment
{
public Random number;
public ArrayList<String> allSubject;
public ArrayList<Subject> allSubjects,alphaSubjects;
public ArrayList<Group> experiment;
public Integer value;
public HashMap<Integer,Subject> matched;
private ArrayList<Integer> numbers;
/**
* Make a new Experiment. Then use method addSubject to add
* Subjects to your experiment. Then call the assignGroups
* method to assign Subjects to each group.
*/
public Experiment()
{
number = new Random();
numbers = new ArrayList<Integer>();
experiment = new ArrayList<Group>();
matched = new HashMap<Integer,Subject>();
allSubjects = new ArrayList<Subject>();
allSubject = new ArrayList<String>();
alphaSubjects = new ArrayList<Subject>();
}
/**
* Alphabetizes the list of Subjects based on their
* name input by the user. As of right now, this method
* is case sensitive meaning Strings starting with
* capitals will be listed before those without capitals.
*/
private void alphabetize()
{
Collections.sort(allSubject);
//compare the String arraylist to the subject arraylist to reset the subject arraylist indeces in alphabetical order.
for(int i =0;i<allSubject.size();i++)
{
String theName = allSubject.get(i);
for(Subject subject:allSubjects)
{
if(subject.getName().toLowerCase().contains(theName))
{
alphaSubjects.add(new Subject(subject.getName(),subject.getDescription()));
}
}
}
}
/**
* Adds a new Subject to the experiment.
*/
public void addSubject(String name, String description)
{
allSubjects.add(new Subject(name,description));
allSubject.add((name.toLowerCase()));
}
So instead of having to add a subject to an arraylist then having to strip the name from that subject and add it to a completely different arraylist, is there a way to alphabetize by the name of the subject.
oh and here is the class: subject.
public class Subject
{
public final String name;
public final String description;
public Subject(String name, String description)
{
this.name = name;
this.description = description;
}
public Subject(int aNumber)
{
name = "Subject" + aNumber;
aNumber++;
description = "default";
}
public String getName()
{
return name;
}
public String getDescription()
{
return description;
}
}

You can wrap subject ArrayList with SortedList(http://www.glazedlists.com/documentation/tutorial-100#TOC-Sorting-Tables-Sorting-Tables) using your own comparator.
SortedList sortedSubjects = new SortedList<Subject>(allSubjects,new Comparator<Subject>() {
#Override
public int compare(Subject left, Subject right) {
return left.getName().compareTo(right.getName);
}
});

All you need to do is have your class implement Comparable and add a compareTo():
public class Subject implements Comparable<Subject>
{
....
#Override
public int compareTo(Subject other)
{
return this.getName().compareTo(other.getName());
}
}
Now, since your class implements Comparable of itself, you can use Collections.sort() to sort your list of Subjects.
Here's a tutorial for more info. Good luck!

You can implement Comparator or Comparable and override compare(..) , compareTo(..) method as per your convince. In your case you need to consider 'name of the subject' while implementing this method. Then Collections.sort(yourList<Subject>) will give you sorted result based on subjects name.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Subject implements Comparable<Subject>
{
public final String name;
public final String description;
public Subject(String name, String description)
{
this.name = name;
this.description = description;
}
public Subject(int aNumber)
{
name = "Subject" + aNumber;
aNumber++;
description = "default";
}
public String getName()
{
return name;
}
public String getDescription()
{
return description;
}
#Override
public int compareTo(Subject o) {
return this.getName().toUpperCase().compareTo(((Subject)o).getName());
}
public static void main(String[] args) {
Subject s3 = new Subject("C","");
Subject s1 = new Subject("Z","");
Subject s2 = new Subject("A","");
List<Subject> list = new ArrayList<Subject>();
list.add(s1);
list.add(s2);
list.add(s3);
Collections.sort(list);
for(Subject sub:list){
System.out.println(sub.getName());
}
}
}

Related

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

How to look though a list of Objects to find a match?

I'm trying to compare a bunch of Objects of the same class to search for matching ID's?
This is the GroupClass, when a new entry is entered it will test against the idNumber to see if there is a match.
Public GroupClass {
private int idNumber;
private String name;
private double income;
public GroupClass(int id, String name, double income){
this.idNumber = id;
this.name = name;
this.income = income;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
}
This is the Main Method
import static java.lang.reflect.Array.set;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class ListTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<GroupClass> groupArray = new LinkedHashSet<>();
System.out.println("Enter a ID Number");
int id = input.nextInt();
System.out.println("Enter a First Name");
String name = input.next();
System.out.println("Enter a an Income");
double income = input.nextDouble();
groupArray.add(new GroupClass(1111, "Billy", 178000));
groupArray.add(new GroupClass(1112, "Sam", 78000));
groupArray.add(new GroupClass(1113, "Mark", 79000));
groupArray.add(new GroupClass(id, name, income));
printTheClass(groupArray);
}
public static void printTheClass(Set group){
for(Object theArray: group){
System.out.println(theArray + " ");
}
}
}
Ive seen a few questions like it but just cant get it to work for my particular case, thanks in advance.
As per the above comment you override the equals method, but this may not be suitable for the long term growth of the class.
But using your existing code try
public static void printTheClass(Set<GroupClass> group){
for(GroupClass theArray: group){
System.out.println(theArray + " ");
}
}
and
public static GroupClass findTheClass(Set<GroupClass> group, int id){
for(GroupClass obj: group){
if(obj.getIdNumber == id) return obj;
}
return null;
}
This can be used as
if (findTheClass (groupArray, id) == null) {
groupArray.add (new GroupClass(id, name, income));
}
Not quite sure what is your goal. If you want to reject any new entry if the id already exist, you need to override the hashCode and equals methods of the GroupClass so that LinkedHashSet knows if two GroupClass objects are different:
#Override
public int hashCode() {
return this.idNumber;
}
#Override
public boolean equals(Object obj) {
return obj instanceof GroupClass && ((GroupClass) obj).getIdNumber() == this.idNumber;
}
However, in most cases, you might want to retrieve an entry using its id number. Then it might be better to use a map with id as key, and the GroupoClass object itself as value
Map<Integer, GroupClass> groupmap = new HashMap<>()
groupmap.put(id, new GroupClass(id, name, income));
and you will have to use groupmap.keySet() to iterate the map.

how to sort a list with different attributes in java

I want sort a list of student object containing attributes name and course such that the sorting is done based on name and if two names are same then it should consider course for sorting... I can do it separately but want a single list... PLz help...
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package studentlist;
import java.util.*;
/**
*
* #author Administrator
*/
public class StudentList {
/**
* #param args the command line arguments
*/
String name, course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public StudentList(String name, String course) {
this.name = name;
this.course = course;
}
public static void main(String[] args) {
// TODO code application logic here
List<StudentList> list = new ArrayList<StudentList>();
list.add(new StudentList("Shaggy", "mca"));
list.add(new StudentList("Roger", "mba"));
list.add(new StudentList("Roger", "bba"));
list.add(new StudentList("Tommy", "ca"));
list.add(new StudentList("Tammy", "bca"));
Collections.sort(list, new NameComparator());
Iterator ir = list.iterator();
while (ir.hasNext()) {
StudentList s = (StudentList) ir.next();
System.out.println(s.name + " " + s.course);
}
System.out.println("\n\n\n ");
Collections.sort(list, new CourseComparator());
Iterator ir1 = list.iterator();
while (ir1.hasNext()) {
StudentList s = (StudentList) ir1.next();
System.out.println(s.name + " " + s.course);
}
}
}
class NameComparator implements Comparator<StudentList> {
public int compare(StudentList s1, StudentList s2) {
return s1.name.compareTo(s2.name);
}
}
class CourseComparator implements Comparator<StudentList> {
public int compare(StudentList s1, StudentList s2) {
return s1.course.compareTo(s2.course);
}
}
You just have to put both the comparison in a single Comparator.
First test the name are equal or not:
If they are not equal, then return the result of comparison of name.
If they are equal, move to compare the courses:
Following comparator would work:
class NameCourseComparator implements Comparator<StudentList> {
public int compare(StudentList s1, StudentList s2) {
if (s1.name.equals(s2.name)) {
return s1.course.compareTo(s2.course);
}
return s1.name.compareTo(s2.name);
}
}
One simple way:
Sort the list according to the name first. After that loop through the list again. If you find any same name in order, then compare the course and update the list accordingly.
You could just tweak the NameComparator a bit
class NameComparator implements Comparator<StudentList> {
public int compare(StudentList s1, StudentList s2) {
if(s1.getName().equals(s2.getName()) {
return s1.getCourse().compareToIgnoreCase(s2.getCourse());
}else {
return s1.getName().compareToIgnoreCase(s2.getName());
}
}

Java List sort on object fields constant values

I have a enum representing severity level
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
}
Person one = new Person();
one.setSeverity(Severity.HIGH);
other fields ...
Person two = new Person();
two.setSeverity(Severity.LOW);
.....
Person three = new Person();
three.setSeverity(Severity.HIGH);
List<Person> persons = Lists.newArrayList();
persons.add(one);
persons.add(two);
persons.add(three);
I would like to sort persons list to sort by severity field (i.e HIGH,MEDIUM then LOW).
My expected results after sorting the persons list should be in the order of HIGH,HIGH,LOW ?
can i know how i can achieve this ?
note : I am making use of com.google.common.collect
Try below code
Create an ENUM
package com.rais;
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String value;
private Severity(String value) {
this.value = value;
}
}
Now Create Person class according to your requirement eg.
package com.rais;
public class Person {
private Severity severity;
private String name;
public Person(Severity severity, String name) {
super();
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Finally create a Test Client and apply below logic.
package com.rais;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestClient {
public static void main(String[] args) {
Person one = new Person(Severity.HIGH, "shayam");
Person two = new Person(Severity.MEDIUM, "mohan");
Person three = new Person(Severity.LOW, "radha");
Person four = new Person(Severity.HIGH, "rakesh");
Person five = new Person(Severity.MEDIUM, "kailash");
Person six = new Person(Severity.LOW, "rais");
Person seven = new Person(Severity.LOW, "abhishek");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
persons.add(four);
persons.add(five);
persons.add(six);
persons.add(seven);
Collections.sort(persons, new Comparator<Person>() {
#Override
public int compare(Person person1, Person person2) {
if(person1.getSeverity()==person2.getSeverity())
{
return person1.getName().compareTo(person2.getName());
}
else{
return person1.getSeverity().compareTo(person2.getSeverity());
}
}
});
for (Person person : persons) {
System.out.println(person.getName()+" "+ person.getSeverity());
}
}
}
I am sure you will get below output.
rakesh HIGH
shayam HIGH
kailash MEDIUM
mohan MEDIUM
abhishek LOW
radha LOW
rais LOW
Use Comparable or comparator and then apply
Collection.sort().
if using comparable interface you have to implement compareTo method and
Collection.sort(<list>)
and if using comparator then you have to override compareTo method and
Collection.sort(<list>, <comparator>)
and when to use comparatot or comparable read link:
http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html
If you are using Google Collections, upgrade to Google Guava. Use its ComparisonChain class. Are you sure you want HIGH, MEDIUM, LOW in that order? The reverse fits Java comparisons better.
How do Persons have a severity level? Perhaps your class deserves a better name.
I would make Person implement Comparable, which makes the sorting code very simple and brief.
Note that enums are implicitly Comparable:
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String code;
private Severity(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
public class Person implements Comparable<Person> {
private Severity severity;
private final String name;
public Person(Severity severity, String name) {
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
#Override
public int compareTo(Person person) {
return severity == person.severity ? name.compareTo(person.name)
: severity.compareTo(person.severity);
}
#Override
public String toString() {
return name + "(" + severity +")";
}
}
Now some test code:
Person one = new Person(Severity.HIGH, "one");
Person two = new Person(Severity.LOW, "two");
Person three = new Person(Severity.HIGH, "three");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
Collections.sort(persons);
System.out.println(persons);
Output:
[one(HIGH), three(HIGH), two(LOW)]

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories