LinkedList with years - java

I have to code LinkedList with two positions. First is the name and the second is the year.
class Person
{
String name;
int year;
public Person(String name, int year) {
this.name = name;
this.year = year;
}
}
class LinkedListStart {
public static void main (String[] args) throws java.lang.Exception
{
LinkedList<Person> persons = new LinkedList<Person>();
persons.add(new Person("Joe", 2010));
persons.add(new Person("Jane", 2012));
persons.add(new Person("Charly", 1910));
persons.add(new Person("Daisy", 1908));
System.out.println("LinkedList : " + persons);
}
}
There are errors when I am running the code:
LinkedList : [Person#6d06d69c, Person#7852e922, Person#4e25154f, Person#70dea4e]
Is it possible to do it? I want do use for-each loop to find person who is below 1950.
How to code something like this?

You should define a class Person as follows:
class Person{
String name;
int year;
public Person(String name, int year) {
this.name = name;
this.year = year;
}
}
And then create a LinkedList as follows:
LinkedList<Person> persons = new LinkedList<>();

You could combine them both into one String like names.add("Joe 2010") (NOT a recommended, or particularly good approach) or create a Person class to include both of these attributes, but you can't add two elements in the space of one, like you are attempting to do with your code above.
If you go with the Person class route, iterate through each element, and check if Person.year or whatever you choose to call the attribute is less than 1950.
If you go with the String route, iterate through each, split the String on a space to create an array, where the first element is the name and the second is the year, parse an int out of the year String using Integer.parseInt and then check if the year is less than 1950. As #Michael mentioned, combining two strings like this is not recommended
Edit: As for your new problem, Java's LinkedList<T> class is known as a generic class, because it takes a type parameter, such as the Person part in LinkedList<Person>. Because your class is not defined as a generic class, and has the same name as the built-in LinkedList, you are receiving this error when you try to pass in a type parameter, as Java thinks you are trying to use your own LinkedList class. In general, even if you are not using a particular built-in class in your code, it's best not to name your own classes with the same name as built-ins, so collisions like this don't happen. Simply rename your own class, and your code will work

Yes you can create a custom list here is the code,
create a class name it what ever you want, i named it HomeDataModel
public class HomeDataModel {
private String name;
private int year;
public HomeDataModel() {
}
public HomeDataModel(String name,int year) {
name=name;
year= year;
}
public String getName() {
return name;
}
public void setName(String name) {
name= name;
}
public String getYear() {
return year;
}
public void setYear(int year) {
year= year;
}
}
now in your activity where you want to use list,,
//creating a custom list
List<HomeDataModel> listname = new ArrayList<>();
list.add(new HomeDataModel("yourname", "Youryear"));
//code for check how is below 1950
for(int i=0; i<listname.size(); i++){
int check = list.get(i).getYear();
if(check <1950){
String newname = list.get(i).getName(); //the name is stored
Toast.makeText(MapsActivity.this,newname, Toast.LENGTH_SHORT).show();
}
}

There are errors when I am running the code: LinkedList : [Person#6d06d69c, Person#7852e922, Person#4e25154f, Person#70dea4e]
Every class in Java has the toString() method in it by default, which is called if you pass some object of that class to System.out.println(). By default, this call returns the className#hashcode of that object.
Here you have not overridden the toString method that's why it is printing like that by default.Please us below code:
public class Test {
static class Person
{
String name;
int year;
public Person(String name, int year) {
this.name = name;
this.year = year;
}
#Override
public String toString() {
return "Person [name=" + name + ", year=" + year + "]";
}
}
public static void main (String[] args) throws java.lang.Exception
{
LinkedList<Person> persons = new LinkedList<Person>();
persons.add(new Person("Joe", 2010));
persons.add(new Person("Jane", 2012));
persons.add(new Person("Charly", 1910));
persons.add(new Person("Daisy", 1908));
for (Person person : persons) {
System.out.println("Name is::"+person.name+" year is:::"+person.year);
}
//for printing the person override tostring method
System.out.println(persons);
}
}

Related

Java: How do I initialize an array with objects of a class at the time of object creation?

I'm working on a code and I want to return the ranking board of the teams in the championship.
I want to make an ArrayList that contain the objects of a class name Team, so I can return the whole ranking board with all the teams .
I want it done at the time of object creation and in this respect I have the following code that is not working:
// the constructor
public Team(String name) {
this.name = name;
teams.add(this);
}
public List<Team<T>> teams = new ArrayList<>();
I have also tried to initialised teams inside a method in which I add the players:
public boolean addMembers(T player) {
if (members.contains(player)) {
System.out.println("Player already in the list");
return false;
} else {
members.add(player);
teams.add(this);
System.out.println(player.getName() + " has been picked for team " + this.name);
returnClassament();
return true;
}
}
this way may be helpful if I did not misunderstand you
public Team(String name, List<Team> list) {
this.name = name;
if(list != null) list.add(this);
}
import java.util.ArrayList;
public class Team{
//we create private variables here because only the constructor is accessing them
private String name;
private int score;
//create a static ArrayList that holds type of class Team here so all objects refer to one and it is not copied over to each object (as per i've learned because static is confusing)
public static ArrayList<Team> teams=new ArrayList<Team>();
public Team(String name,int score){
this.name=name;
this.score=score;
//tell the program that the instance variable has the same value as the parameter
teams.add(this);
//adding the object to the ArrayList
}
//This is not necessary; it just prints the values of each object in the ArrayList
public void printTeamStats(){
System.out.println(name+" "+score);
}
}
The AddPlayer method of the Championship class can be used to add a player to the system
Void addPlayer (String surname, Strong country, integer age, String position) {

String alphabetical order using List or Arraylist [duplicate]

This question already has answers here:
How to sort List of objects by some property
(17 answers)
Closed 3 years ago.
In this program I sorted strings in Alphabetic way in Simple Array but how can I do the same thing using List or ArrayList, Suppose I have a class Students and I want to order names in an alphabetically way, so how can I do that?
public class CityData{
public static String citynames[]= {"Hyderabad","Karachi","Abtabad","AzadKashmir"};
public static void main(String args[]) {
int size=citynames.length;
String temp=null;
for(int i=0; i<size; i++) {
for(int j=i+1; j<size; j++) {
if(citynames[i].compareTo(citynames[j])>0) {
temp=citynames[i];
citynames[i]=citynames[j];
citynames[j]=temp; }
}
System.out.println(citynames[i]);
}
}
}
Result:
Abtabad
AzadKashmir
Hyderabad
Karachi
You can sort the collections based on your requirements.
If the input objects for collections is implementing the Comparable interface like String, Integer, Double classes, then you can directly use Collections.sort() method from Collections util class
List<String> al = new ArrayList<>();
al.add("Hyderabad");
al.add("Karachi");
al.add("Abtabad");
al.add("AzadKashmir");
al.add("Udupi");
al.add("Jammu");
Collections.sort(al);
Or you can sort the list based on your requirement.(Reverse alphabetical Order)
Collections.sort(al, (str1, str2) -> str2.compareTo(str1));
If you don't want to use the Collections class, then directly use the sort() method present in List interface.
i. Albhabetical Order
al.sort((str1, str2) -> str1.compareTo(str1));
ii. Reverse Albhabetical Order
al.sort((str1, str2) -> str2.compareTo(str1));
The above solution is for the Objects where the class implements the Comparable Interface like String, Integer, Double, etc...
When to sort the Custom Classes, you need to implement sort by Comparator class or Lambda expression for the Comparator.
Consider you have a Student Class, and need to sort by city names. You can use below code.
Student Class
public class Student {
private String name;
private String city;
public Student() {}
public Student(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Student -> [name=" + name + ", city=" + city + "]";
}
}
Sorting By Collection Class sort() method
Student st1 = new Student("Samir", "Hyderabad");
Student st2 = new Student("Akbar", "Karachi");
Student st3 = new Student("Ramu", "Abtabad");
Student st4 = new Student("Rahim", "AzadKashmir");
Student st5 = new Student("Sardar", "Udupi");
Student st6 = new Student("Fahad khan", "Jammu");
List<Student> al2 = new ArrayList<>();
al2.add(st1);
al2.add(st2);
al2.add(st3);
al2.add(st4);
al2.add(st5);
al2.add(st6);
//Alphabetical Order
Collections.sort(al2, (std1, std2) -> std1.getCity().compareTo(std2.getCity()));
//Reverse Alphabetical Order
Collections.sort(al2, (std1, std2) -> std2.getCity().compareTo(std1.getCity()));
By using List.sort() method
//Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));
//Reverse Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));
What you are looking for is actually pretty simple to do:
Instead of using citynames[i] or citynames[j], for Lists and ArrayLists, you use citynames.get(i) or citynames.get(j).
Just think of List.get() is the same as the brackets you put before for the simple arrays.
Just remember, when you want to set a value, you actually have to use the List.set(int index, Object value).
The same can be said if you are trying to get the length of the List or ArrayList. You can simply replace citynames.length to citynames.size();
public static void main(String args[]) {
int size=citynames.size();
String temp=null;
for(int i=0; i<size; i++) {
for(int j=i+1; j<size; j++) {
if(citynames.get(i).compareTo(citynames.get(j))>0) {
temp=citynames.get(i);
citynames.set(i, citynames.get(j));
citynames.set(j, temp); }
}
System.out.println(citynames.get(i));
}
}
Update: Better Solution:
Note: When using Collections.sort() it is important to make sure the object type of the array implements Comparable. the Collections.sort() uses the compareTo() within the object class to sort the elements.
public class Main(){
import java.util.Collections;
public static void main(String args[]) {
ArrayList<City> citynames = new ArrayList<City>();
citynames.add("Hyderabad");
citynames.add("Karachi");
citynames.add("Abtabad");
citynames.add("AzadKashmir");
Collections.sort(citynames);
for(cityname : citynames)
System.out.println(cityname);
}
}
public class City implements Comparable{
private String name;
// Constructor
public City(String name){
this.name = name;
}
// Getter method
public String getName(){
return name;
}
// compareTo Method
public int compareTo(City other){
return name.compareTo(other.getName());
}
// Other methods may exist
}
For more information: https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
I do not have the rights to comment yet, hence adding at as an answer.
You can google this easily and also lookup API for sorting collections.
Code in java 8
public class ArrayListSort {
public static String citynames[] = { "Hyderabad", "Karachi", "Abtabad", "AzadKashmir" };
public static void main(String args[]) {
Student stud1 = new Student("Alex", 20);
Student stud2 = new Student("Bryan", 21);
Student stud3 = new Student("Chris", 22);
Student stud4 = new Student("Dan", 23);
List<Student> students = new ArrayList<>(Arrays.asList(stud4, stud3, stud2, stud1));
Collections.sort(students);
for(Student stud: students){
System.out.println(stud.getName());
}
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return age;
}
#Override
public int compareTo(Student other) {
return this.name.compareTo(other.name);
}
}
Edit 1 to answer your comment, look up Comparable interface

Sort HashMap by value which is an instance of a class with multiple variables

my first post here & I'm only starting to learn Java so please bear with me.
I have a HashMap which stores a key and an instance of a class as the corresponding value (from a class I called Main). The object has a two variables. What I'd like to do is to get a print out based on a particular object variable, in this example by year. Here is my code:
public class Main {
private String name;
private int year;
public Main(String name, int year) {
this.name = name;
this.year = year;
}
protected static Map<Integer, Main> input = new LinkedHashMap<Integer, Main>();
input.put(1, new Main("Chris", 1980);
input.put(2, new Main("Daphne", 1981);
input.put(3, new Main("Sandra", 1976);
input.put(4, new Main("Adele", 1980);
So now what I'd like to be able to do is to list everyone by year. So my expected output would look like this:
1976: Sandra
1980: Chris, Adele
1981: Daphne
Many thanks
One way to do it is to use a stream, for example:
Map<Integer,List<Main>> mainByYear = input.values().stream().collect(Collectors.groupingBy
(e -> e.year));
Then you can iterate through the mainByYear map to print out the key, and the associated list members.
Using streams you can do:
public class Main {
private String name;
private int year;
public Main(String name, int year) {
this.name = name;
this.year = year;
}
public String getName() {
return name;
}
public int getYear() {
return year;
}
public static void main(String[] args) {
Map<Integer, Main> input = new LinkedHashMap<>();
input.put(1, new Main("Chris", 1980));
input.put(2, new Main("Daphne", 1981));
input.put(3, new Main("Sandra", 1976));
input.put(4, new Main("Adele", 1980));
input.entrySet().stream().map(Map.Entry::getValue)
.collect(Collectors.groupingBy(Main::getYear))
.forEach((key, value) -> System.out.println(
key + ": " + String.join(", ", value.stream().map(Main::getName)
.collect(Collectors.toList()))));
}
}

What's the importance in using the set method when the attributes have already been defined in the Used Defined Constructor? [duplicate]

This question already has answers here:
Setter methods or constructors
(10 answers)
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
In the below code I've already declared that room = r; subject = s; and time = t; in the user defined constructor, so why is it necessary to do so again in set methods, my lecturer specifically asked that we add set methods for the room subject and time but it's redundant code as when I comment it out it still works. Do you only need to include set methods when there is no used defined constructor? What could be the advantage of having them set methods there?
class LectureTest{
public static void main (String [] args){
Lecture l1 = new Lecture(140, "Comp", 5);
l1.display();
Lecture l2 = new Lecture(280, "Sports", 3);
l2.display();
Lecture l3 = new Lecture(101, "Business", 5);
l3.display();
Lecture l4 = new Lecture(360, "Shooting", 4);
l4.display();
Lecture l5 = new Lecture();
l5.display();
}
}//end of LectureTest
class Lecture{
private int room;
private String subject;
private int time;
Lecture(int r, String s, int t){
room = r;
subject = s;
time = t;
}
Lecture(){}
public void setroomNumber(int r){
room = r;
}
public void setSubject(String s){
subject = s;
}
public void setTime(int t){
time = t;
}
public int getroomNumber(){
return room;
}
public String getSubject(){
return subject;
}
public int getTime(){
return time;
}
public void display(){
System.out.printf("\n" + "Room Number: " + getroomNumber() + "\n" + "Subject: " + getSubject() + "\n" + "Time " + getTime() + "\n");
}
}
The constructor "initializes" your values.
Let's say you have...
public class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
String str;
str = "My name is "+name+" and I am "+age+" years old!";
return str;
}
}//End of Person
public class Main {
public static void main(String [] args) {
Person person = new Person("Bob", 15);
System.out.println(person.toString());
System.out.println("Switching my name...");
person.setName("Joe");
System.out.println(person.toString());
}
}//End of main
You see the difference? You should use the constructor if you want to create a new instance of the object. This way, you can set all the fields of the object at once and not need to call 490832490 setters (in this case, one for name and one for age...). You then can use the setter approach when you want to change the value of a field, PRIOR TO the object been created.
I DID ALL THIS ON THIS FORUM SO I MIGHT HAVE SYNTAX ERRORS SO CAREFUL...DIDN'T USE AN IDE IF YOU WANT TO TEST IT
The set methods make your object mutable. If you don't have the set methods and your variables are private then the Object will be immutable. You won't be able to change the values after it is constructed...If the values need to change you would have to create a new Object.
"Setters" allow you to modify private attributes of your object after instantiating. For example:
Lecture l1 = new Lecture(140, "Comp", 5);
//Since "room" is private you can't write l1.room = 4
//and have to use the setter method instead:
l1.setroomNumber(4);
l1.display();
They are also very useful if you want to do something if an attribute changes.
Let's assume you are using Observers, then you could call notifyObservers() or setChanged() in your setter method and never have to worry about these methods not getting called if your attribute changes.

Half completed codes for arraylist

I am having my final exam tomorrow so i am practicing some questions.But i am stuck at this question.I am given a person class file and a half completed quiz10 file whereby i have to fill up.The quiz10 codes are halfway done(given).
I need to implement a function findPersonWhoseNameStartWith which returns the names of the persons in the list who start with A. But i have no idea how.
Output wanted:
result:April,Adam
public class Person{
private int age;
private String name;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String toString(){
return "" + name;
}
}
Half given codes(I have indicate which part i have attempted):
import java.util.*;
public class Quiz10{
public static void main(String[] args){
ArrayList<Person>list=new ArrayList<Person>();
list.add(new Person("April",9));
list.add(new Person("Adam",3));
list.add(new Person("bil",9));
list.add(new Person("cpril",9));
list.add(new Person("dpril",9));
ArrayList<Person>result=findPersonWhoseNameStartWith(list,"A");
System.out.println("result:");
//START DOING FROM HERE
for(int i=0;i<list.size();i++){
Person p=list.get(i);
if(p.findPersonWhoseNameStartWith("A");
}
}
You are on the right track. you are right you have to iterate over the list. Now for each entry output it if it starts with 'A'. It's very simple and a single if statement way easier than what you imagine it seems.
// pass your personList and the prefix, return a list of person starting with the prefix you specified
private List<Person> findPersonWhoseNameStartWith(List<Person> personList, String prefix) {
// create a list to store your result
List<Person> matchedList = new ArrayList<Person>();
// TODO iterate personList
// add them to the matchedList if the prefix matches
return matchedList;
}
public List<Person> findAPersonWhoStartsWith(List<Person> persons, String aLetter){
List<String> personsNames = new ArrayList<String>();
if(persons!=null && aLetter!=null && !aLetter.isEmpty()){
for(Person aPerson:persons){
if(aPerson.getName().startsWith(aLetter)){
personsNames.add(aPerson);
}
}
}
return personsNames;
}

Categories

Resources