Getting average data from list using Collectors.averagingInt java - java

I have a code with two different methods, but one of them is working and other is not compilled, I don`t get what is wrong.
Here is the code:
public class CollectorOperations {
public int averageAgeInt(List<Person> persons) {
return persons.stream()
.collect(Collectors.averagingInt(person -> person.getAge()));
}
public double averageAgeDouble(List<Person> personList, int i) {
return personList.stream()
.collect(Collectors.averagingInt(person -> person.getAge()));
}
}
class Person {
private String name;
private String lastName;
private int age;
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public Person(String name, String lastName, int age) {
this.name = name;
this.lastName = lastName;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The only difference between this two methods is return type, when return type is int I can't get person.age() from lambda expression, but when I change return type to double it's working.
P.S.
sorry for my english.

It is not compiling due a type mismatch here:
persons.stream().collect(Collectors.averagingInt(person -> person.getAge()));
That operation returns an object of the type Double, but your method is defined to return an integer.
The reason is that a Double object can not be cast into an int, but since that is a Double object, you can get the integer value calling the method Double#intValue()
You need to do something like
return persons.stream().collect(Collectors.averagingInt(person -> person.getAge())).intValue();
I don’t get why you have a parameter int i in the method averageAgeDouble (the variable is never used), so you can define a more elegant way if you get rid off that variable:
public int averageAgeInt(List<Person> persons) {
return (int) averageAgeDouble(persons);
}
public double averageAgeDouble(List<Person> personList) {
return personList.stream().collect(Collectors.averagingInt(person -> person.getAge()));
}

Related

Got stuck at step 4

Create a Student Class with the following instance variables:
-LastName
-MatNo
-Age
-GPA e.g A+, B-```
Create a Constructor that takes all the instance variables (class fields) as input parameters.
Create Accessor(Getter) and Mutator (Setter) methods for each of the instance variables.
Create a method called calAge that returns the age of a student based on yearofBirth as input parameter.
Create a Tester Program to test the Student class. Do the following:
-Calculate the age of each student object created based on the calAge method.
-Change the GPA of each student by calling the Mutator method of GPA.
-Make sure data about each of the students is printed to the Console.```
My code so far:
package ict;
public class Student {
private String firstName;
private String lastName;
private int mattNo;
private int age;
private String gpa;
public Student(String first, String last, int matt, int ag, String gp)
{
setFirstName(first);
setLastName(last);
setMattNo(matt);
setAge(ag);
setGpa(gp);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getMattNo() {
return mattNo;
}
public void setMattNo(int mattNo) {
this.mattNo = mattNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGpa() {
return gpa;
}
public void setGpa(String gpa) {
this.gpa = gpa;
}
}
Create a method called calAge that returns the age of a student based
on yearofBirth as input parameter.
int calAge (int yearofBirth) {
Year y = Year.now();
return y.getValue () - yearOfBirth;
}
now this does not seem to be a very good way, I think you need to consider the month and day that you were born.
also consider to make this method static

Deserialization fails when there is no default constructor

I 'm trying to use Fastjson library for JSON serialization.
When I try to deserialize , it fails showing no default constructor error.
Note: My class here is a toy example. I realty, it contains so many references to other classes which are in other maven projects and its practically not possible to modify every class.
Here is the code.
Student s = new Student("vineel", "20");
String hell = JSON.toJSONString(s);
Student model2 = JSON.parseObject(hell, Student.class);
System.out.println(model2);
public class Student {
private String name;
private String age;
Student(String name,String age){
this.name = name;
this.age = age;
}
#override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Here is the error:
Exception in thread "main" com.alibaba.fastjson.JSONException: default constructor not found. class com.alibaba.fastjson.Student
at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:467)
at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:213)
at com.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:656)
at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:573)
at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:386)
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:658)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:365)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:269)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:488)
at com.alibaba.fastjson.JSON.main(JSON.java:1068)
Change constructor to.
#JsonCreator
public Student(#JsonProperty("name") String name, #JsonProperty("age") String age){
this.name = name;
this.age = age;
}
So create a TO class.
Student model2 = JSON.parseObject(hell, StudentTO.class).asStudent();
System.out.println(model2);
public class StudentTO {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Student asStudent() {
return new Student(name, age);
}
}

Overloaded constructors in a class

I'm doing a project with overloaded constructors in a class and I'm a little stuck, below is what I'm supposed to be doing with the overloaded constructors:
"One that allows first, middle, and last names to be passed as Strings with an int for age
One that accepts a Name object reference, and an age as an int
Make a new Name inside Person, copying the references for the parts of the name."
I'm not quite sure what to do with my code, here is what I got:
public class Person {
int age;
Name aPersonHasAName;
Name newPerson = new Name();
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName = middleName;
newPerson.lastName = lastName;
}
public Person(Name aPersonHasAName, int age) {
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I'm just lost as to what I'm supposed to be typing. I believe I've done the first overloaded constructor, but I am new to this.
So what should I be doing to make this work with overloaded constructors?
I think having the code from the other two classes might help.
Here is PersonTester:
public class PersonTester {
public static void main(String[] args) {
Person person1 = new Person("a1", "b1", "c1", 11);
Person person2 = new Person(new Name("a2", "b2", "c2"), 22);
Person person3 = new Person(new Name("a3", "c3"), 33);
Person person4 = new Person(new Name("a4"), 44);
Person person5 = new Person(new Name(), 55);
System.out.println(person1.details());
System.out.println(person2.details());
System.out.println(person3.details());
System.out.println(person4.details());
System.out.println(person5.details());
}
}
Then here is the Name class:
public class Name {
String firstName;
String middleName;
String lastName;
public Name(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
public Name(String firstName, String lastName) {
this(firstName, "", lastName);
}
public Name(String firstName) {
this(firstName, "", "");
}
public Name() {
this("", "", "");
}
public String getLastName() {
return lastName;
}
public String getMiddleName() {
return middleName;
}
public String getFirstName() {
return firstName;
}
public String getFullName(String nameString) {
StringBuilder build = new StringBuilder();
build.append(nameString);
build.deleteCharAt(nameString.length() - 1);
build.insert(0, build.hashCode());
return build.toString();
}
}
The problem I am having now is the error message in PersonTester which is: The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I just need to know what in which class needs to be fixed to make it work.
I am very new to Java and object oriented programming.
So far so good. But eventually you'll reach a point where you duplicate a fair bit of code.
The constructor
public Person(String firstName, String middleName, String lastName, int age) {
is the most comprehensive one in the sense that it takes in all the possible data.
With the other constructors, say one that takes a last name and an age, you can use delegating constructors:
public Person(String lastName, int age) {
this(null, null, lastName, age); /*calls the other constructor*/
}
If you can't make such an assumption then you'll need to split up the name string by hand.
Updating your code:
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName =
newPerson.lastName = lastName;
this.age = age; //<---- was missing in your code
}
And your second contructor may look like this:
public Person(Name aPersonHasAName, int age) {
this.newPerson = aPersonHasAName;
this.age = age;
}
These contructors are implemented as you needed.
Notice that you already done your overloading, if you got multiple constructors with not the same titles you contructors overloading
public class Person {
int age;
Name aPersonHasAName;
public Person(String firstName, String middleName, String lastName, int age) {
aPersonHasAName = new Name();
aPersonHasAName.firstName = firstName;
aPersonHasAName.middleName = middleName;
aPersonHasAName.lastName = lastName;
this.age = age;
}
public Person(Name aPersonHasAName, int age) {
this.aPersonHasAName = aPersonHasAName;
this.age = age;
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I guess it also depends on if Name has a constructor for firstName, middleName, lastName

Work with methods, setters and getters in java

I have this class:
public class Person
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String firstName = "Vasya";
private String lastName = "Pupkin";
private Integer age = 58;
private Integer phone = 2;
#Override
public String toString()
{
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ ", age=" + age + "]";
}
public void setName(String name)
{
firstName = name;
}
public void setLastName(String lName)
{
lastName = lName;
}
public void setAge(Integer personAge)
{
age = personAge;
}
public void setPhone(Integer personPhone)
{
phone = personPhone;
}
public String getName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public Integer getAge()
{
return age;
}
public Integer getPhone()
{
return phone;
}
public void Init()
{
this.setName("");
this.setLastName("");
this.setPhone(0);
this.setAge(0);
}
}
I create an variable: Person somePerson, then I call method setName from that variable somePerson:
somePerson.setName("");
but it raises an error.
Based on the provided code, the following should work:
Person somePerson = new Person();
somePerson.setName("");
If it doesn't, then something else is going on.

sorting an arrayList<class> by its integer contents

I am passing an arrayList to a method to sort its data.
The data in the arrayList would contain multiple id numbers correlating to different students.
the array will also include other information. How do i sort the arrayList by its id #. I believe it will have to do with my created class which is included below
more code can be provided as necessary
public static class Student {
public String firstName;
public String lastName;
public Integer uid;
public StudentType type;
public Student(Student orig) {
this.firstName = orig.firstName;
this.lastName = orig.lastName;
this.uid = orig.uid;
this.type = orig.type;
}
// construct a new student with given fields
public Student(String firstName, String lastName, Integer newUid, StudentType type) {
this.firstName = firstName;
this.lastName = lastName;
this.uid = newUid;
this.type = type;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
//set type
public void setType(StudentType type) {
this.type = type;
}
//return type
public StudentType getType() {
return type;
}
public void setUid(Integer uid){
this.uid = uid;
}
public Integer getUid() {
return uid;
}
// return a string representation of the invoking object
public String toString() {
return firstName + " " + lastName + " " + uid + " " + type;
}
public static class Graduate extends Student {
public boolean thesis;
public ClassStanding study;
public String profName;
public Graduate(Student orig, boolean isThesis, ClassStanding study, String profName) {
super(orig);
thesis = isThesis;
this.study = study;
this.profName = profName;
}
public boolean getThesis() {
return thesis;
}
public void setThesis(Boolean thesis) {
this.thesis = thesis;
}
public ClassStanding getStudy() {
return study;
}
public void setStudy(ClassStanding study) {
this.study = study;
}
public String getProfName() {
return profName;
}
public void setProfName(String profName) {
this.profName = profName;
}
public String toString() {
return super.toString() + thesis + " " + study + " " + profName;
}
}
public static class UnderGraduate extends Student {
public Major major;
public Double overallGpa;
public Double majorGpa;
public ClassStanding study;
public UnderGraduate(Student orig, Major major, Double overallGpa, Double majorGpa, ClassStanding study) {
super(orig);
this.study = study;
this.major = major;
this.overallGpa = overallGpa;
this.majorGpa = majorGpa;
}
public void setMajor(Major major) {
this.major = major;
}
//return type
public Major getmMajor() {
return major;
}
public void setOverallGPA(Double overallGpa) {
this.overallGpa = overallGpa;
}
public Double getOverallGPA() {
return overallGpa;
}
public void setMajorGPA(Double majorGpa) {
this.majorGpa = majorGpa;
}
public Double getMajorGPA() {
return majorGpa;
}
public ClassStanding getStudy() {
return study;
}
public void setStudy(ClassStanding study) {
this.study = study;
}
public String toString() {
return study + " " + major + " " + overallGpa + " " + majorGpa;
}
}
}
Collections.sort(myListofStudents, new Comparator<Student>() {
#Override
public int compareTo(Student s1, Student s2) {
return s1.getUid().compareTo(s2.getUid());
}
});
Alternatively, you can have Student implement Comparable<Student>, which means including a .compareTo().
NB: If you're going to override .compareTo(), you should override .equals(), which means you should override hashCode().
Define a Comparator<Student> and use it with Collections.sort:
public class StudentComparator implements Comparator<Student> {
#Override
public int compare (Student s1, Student s2) {
// Your comparison logic here
}
}
...then...
Collections.sort(data, new StudentComparator());
See the JavaDoc on Comparator for more information.
Create a Comparator for Student, then use Collections.sort()

Categories