Java issue reusing list to populate HashMap - java

I'm trying to set HashMap values in java whilst trying to reuse an arrayList. I hadn't worked with HashMaps before and am still get my head around this, so please bear with my limited knowledge.
Class Student:
public class Student {
private static int id = 0;
private String name;
private String surname;
private Map<Subject, List<Grade>> grades;
private List<Absence> absences;
}
grades setter:
public void setGrades(Map<Subject, List<Nota>> grades) {
this.grades = grades;
}
Class Subject:
public class Subject {
private String name;
}
Class Grade:
public class Grade {
private Term term;
private String letter;
}
Main program:
Subject subject = new Subject("History");
Map<Subject, List<Grade>> gradeMap = new HashMap<Subject, List<Grade>>();
List <Grade> grades = new ArrayList<Grade>();
grades.add(new Grade(Term.FIRST_TERM, 'A'));
grades.add(new Grade(Term.SECOND_TERM, 'F'));
grades.add(new Grade(Term.THIRD_TERM, 'B'));
gradeMap.put(subject, grades);
student1.setGrades(gradeMap);
Test printing the keys and values :
for(Map.Entry<Subject, List<Grade>> t :student1.getGrades().entrySet()){
Subject key = t.getKey();
for (Grade grade : t.getValue()) {
System.out.println(key.getName() + " - " + grade.getNumber());
}
}
But whenever i try to reutilize the ArrayList, since there are many students whose grades need setting, I lose all data in my student1 instance
grades.clear();
If I try printing to console now the output is empty:
for(Map.Entry<Subject, List<Grade>> t :student1.getGrades().entrySet()){
Subject key = t.getKey();
for (Grade grade : t.getValue()) {
System.out.println(key.getName() + " - " + grade.getNumber());
}
}
I would really appreciate any comments and suggestions on this, clearly I must be doing something wrong but I don't know what :D
Thanks in advance!

What you put in the map is a reference to that same list you still have. It didn't create a copy of it (as Java doesn't do such things), what you hold is still that same list that's in the map. If you want a new one you need to create it manually:
grades = new ArrayList<>();
And than the only reference to the one with Student1 record will indeed be in that map.
See Is Java "pass-by-reference" or "pass-by-value"? for more details.

Related

How to inject function to method in java to reduce code repetition?

I'm currently learning Java and during my current project I need to print stats of students depending on the different courses: "Java", "DSA", "Databases", "Spring". I managed to get right data but as you can see below in code it is to many code repetition. Do you know maybe how to inject e.g. getJavaPoints() function when "Java" String is passed to printInfoAboutTopLearners(String courseName) method?
I don't use DB as repository currently as it is just learning project the repository is ArrayList<<Student>Student>.
The goal is to simplify code below:
public static void printInfoAboutTopLearners(String courseName) {
System.out.println(courseName);
System.out.println("id points completed");
ArrayList<Student> students = StudentRepository.getStudentRepository();
if (courseName.equals("Java")) {
students
.stream()
.sorted(Comparator.comparingInt(Student::getJavaPoints).reversed())
.filter(student -> student.getJavaPoints() != 0)
.forEach(student -> System.out.printf(Locale.US,
"%d %-8d %.1f%%\n",
student.getId(),
student.getJavaPoints(),
(double) student.getJavaPoints() * 100 / JAVA_POINTS));
}
if (courseName.equals("DSA")) {
students
.stream()
.sorted(Comparator.comparingInt(Student::getDsaPoints).reversed())
.filter(student -> student.getDsaPoints() != 0)
.forEach(student -> System.out.printf(Locale.US,
"%d %-8d %.1f%%\n",
student.getId(),
student.getDsaPoints(),
(double) student.getDsaPoints() * 100 / JAVA_POINTS));
}
if (courseName.equals("Databases")) {
students
.stream()
.sorted(Comparator.comparingInt(Student::getDbPoints).reversed())
.filter(student -> student.getDbPoints() != 0)
.forEach(student -> System.out.printf(Locale.US,
"%d %-8d %.1f%%\n",
student.getId(),
student.getDbPoints(),
(double) student.getDbPoints() * 100 / JAVA_POINTS));
}
if (courseName.equals("Spring")) {
students
.stream()
.sorted(Comparator.comparingInt(Student::getSpringPoints).reversed())
.filter(student -> student.getSpringPoints() != 0)
.forEach(student -> System.out.printf(Locale.US,
"%d %-8d %.1f%%\n",
student.getId(),
student.getSpringPoints(),
(double) student.getSpringPoints() * 100 / JAVA_POINTS));
}
}
Below Student class:
public class Student {
private final int ID_BASE = 10000;
private int id;
private String firstName;
private String lastName;
private String email;
private int javaPoints;
private int dsaPoints;
private int dbPoints;
private int springPoints;
public Student(String firstName, String lastName, String email) {
this.id = idGenerator();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.javaPoints = 0;
this.dsaPoints = 0;
this.dbPoints = 0;
this.springPoints = 0;
}
public int idGenerator(){
return ID_BASE + StudentRepository.getSize();
} //Getters and Setters below
This is how I would model this:
public record Student(String firstName, String lastName, String studentID) {}
public record Course(String name, String id, Gradebook gradebook) {}
Student and Course objects should not (or need not) be directly related to each other. A student doesn't have a course. A student is ENROLLED in a course. Likewise, a course doesn't have a student. Attributes of a course should be limited to at least its name and its ID. A course could have other attributes like section ID, a boolean flag for availability, capacity (max number of seats), and description. I used Java records to eliminate boilerplate code. Also, these objects are immutable (and inherently thread-safe) because there is no reason to mutate them once they are created. I can still mutate the gradebook as you will see later on.
You then need to create classes that will complete the association between a student and a course. Something that comes to mind is Enrollment. In this class, you will have a list of courses containing a list of students enrolled in the particular courses. For this, I will use a class.
public class Enrollment {
private Map<Course, List<Student>>
// rest of class omitted
}
This is an entity a registrar's office would need. For this example, I indicated that Gradebook is an attribute of Course record. This means that Course object has-a Gradebook. A gradebook is a record of students and their particular grades. This is the class that, for your example, links or associates students and course grades.
public class Gradebook {
private Map<Student, List<Integer>> grades = new HashMap<>(); // mapping of student IDs and course grades
public List<Integer> getGrades(Student student) {
return grades.get(student);
}
public double getGPA(Student student) {
return getGrades(student).stream().mapToInt((x) -> x).summaryStatistics().getAverage();
}
public void addStudent(Student student) {
grades.put(student, new ArrayList<Integer>());
}
public void enterStudentGrade(Student student, int points) {
List<Integer> gradePoints = grades.get(student);
gradePoints.add(points);
grades.put(student, gradePoints);
}
public TopPerformer getTopPerformer() {
Map.Entry<Student, Double> topPerformer = grades.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
e-> e.getValue()
.stream()
.mapToInt(Integer::intValue)
.average()
.getAsDouble())).entrySet().stream().max((Entry<?, Double> e1, Entry<?, Double> e2) -> e1.getValue()
.compareTo(e2.getValue())).get();
String name = topPerformer.getKey().firstName() + " " + topPerformer.getKey().lastName();
return new TopPerformer(name, topPerformer.getValue());
}
public record TopPerformer(String name, double points) {}
}
It is worth noting that I didn't use a record for the gradebook because I want to be able to update (mutate) gradebooks after they are initially created.
Now that you have this framework in place, you can create a function to figure out (calculate) the top performers for each course. The question is: where do you put this method? IMO, since a Gradebook instance contains a record of students and their particular grades, you can have this class calculate the averages and return its top student. For simplicity, I added it to this class. I also believe it belongs here since the purpose of the Gradebook class is to manage student grades and calculating the top performer seems to be a derived functionality of this class. I also added the following main method to this class to test the code:
public static void main(String[] args) {
Student steve = new Student("Steve", "Jobs", "12345");
Student bill = new Student("Bill", "Gates", "67890");
Student john = new Student ("John", "Doe", "98765");
Student jane = new Student ("Jane", "Doe", "31245");
Course java = new Course("Java", "COMP1010", new Gradebook());
Course dsa = new Course("DSA", "COMP1020", new Gradebook());
dsa.gradebook().addStudent(john);
dsa.gradebook().addStudent(bill);
java.gradebook().addStudent(steve);
java.gradebook().addStudent(jane);
java.gradebook().enterStudentGrade(jane, 100);
java.gradebook().enterStudentGrade(jane, 95);
java.gradebook().enterStudentGrade(jane, 97);
java.gradebook().enterStudentGrade(steve, 96);
java.gradebook().enterStudentGrade(steve, 95);
java.gradebook().enterStudentGrade(steve, 97);
dsa.gradebook().enterStudentGrade(bill, 100);
dsa.gradebook().enterStudentGrade(bill, 95);
dsa.gradebook().enterStudentGrade(bill, 97);
dsa.gradebook().enterStudentGrade(john, 96);
dsa.gradebook().enterStudentGrade(john, 95);
dsa.gradebook().enterStudentGrade(john, 97);
System.out.println(java.gradebook().getTopPerformer());
System.out.println(dsa.gradebook().getTopPerformer());
}
There is no branching to figure out the course name and do the calculation for top performer. No matter what course it is (current or one that doesn't exist today), it calculates the top performer using the same function; which goes to the heart of your question which was eliminate duplicate code.
Executing the code above outputs the following:
TopPerformer[name=Jane Doe, points=97.33333333333333]
TopPerformer[name=Bill Gates, points=97.33333333333333]
The TopPerformer object doesn't need to be a record. It also doesn't need to be a class. You could simply modify the code slightly and return a map of the top student and his or her GPA.
You have a lot going on here, so without re-writing everything myself, I would suggest you embrace OOD and re-work your classes a bit. You already have a Student class. You should also had a Course class that contains a Map of students with their scores. You can then remove the various point fields from your student class. I'd also keep a CourseRepository class.
Course's have Students, Students don't have Courses.
Then your logic would go something like:
Get Course from CourseRepository using the courseName
Get Get the list of Students and their scores from the Course
Sort the list
Output the list
Though there are other improvement areas like class design etc. as suggested in other answers. Below code demonstrates injecting a function to a method to take out specifics out of the method while keeping only common logic inside. This method is then typically be called "higher order function" in functional programming paradigm terminology.
public static void printInfo(String courseName) {
switch (courseName) {
case "Java":
printInfoAboutTopLearners(Student::getJavaPoints);
break;
case "DSA":
printInfoAboutTopLearners(Student::getDsaPoints);
break;
case "Databases":
printInfoAboutTopLearners(Student::getDbPoints);
break;
case "Spring":
printInfoAboutTopLearners(Student::getSpringPoints);
}
}
public static void printInfoAboutTopLearners(Function<Student, Integer> valueGetter) {
System.out.println("id points completed");
List<Student> students = StudentRepository.getStudentRepository();
students
.stream()
.sorted(Comparator.comparing(valueGetter).reversed())
.filter(student -> valueGetter.apply(student) != 0)
.forEach(student -> System.out.printf(Locale.US,
"%d %-8d %.1f%%\n",
student.getId(),
valueGetter.apply(student),
(double) valueGetter.apply(student) * 100 / JAVA_POINTS));
}

How to make two Java arrays correspond to each other (Beginner)

I am creating a simple command-line application where student courses and the corresponding grades the students achieved for them are inputted. I have created two arrays - one to store the student courses, and another to store the corresponding grades.
String[] courses = {"Computer Science", "Maths", "English"};
int[] grades = {5, 4, 3}
How do I make the each grade correspond to each subject, so Computer Science has a grade of 5.
I'm guessing theres a much more efficient way of doing this, but as a newbie I would appreciate any pointers in the right direction. Ideally I want to store all the info in one array.
It doesn't make sense to bind those two arrays. In Java it's better to use objects. If you want to storage those data together (grades and courses) - create a class, after that creat objects that class and put them into array, like the following code:
public class Main {
public static void main(String args[]){
Grades[] grades = {
new Grades("Computer Science", 5),
new Grades("Math", 4),
new Grades("English", 3)
};
for (int i = 0; i < grades.length; i++){
System.out.println(grades[i]);
}
}
}
class Grades{
String subjectName;
int grade;
public Grades(String subjectName, int grade) {
this.subjectName = subjectName;
this.grade = grade;
}
#Override
public String toString() {
return "Grade is: " + this.grade + "\n" +
"Subject is: " + this.subjectName;
}
}
If you know what extension is the code above gives you enough information to realize your diagram, good luck!

how to implement Custom Auto suggestion in java like google

how to implement Java Based Auto suggestion. suppose I have different types of data like firstName, rollNumber, address.
My first requirement is like if user enter first character on text box, then result should be sorted on natural order based on firstName and 10 results should be display.
after space if use enter second character and if it is numbere then RollNumber else lastName should be sorted on natural order as ascending.
or if user type third character then Address should be display on ascending order. there should be no database, you don't have to implement Solr or other api. how to implement on pure Java.
here I did not implement the text-box,but I Just took an example to demonstrate
import java.util.*;
import java.lang.*;
import java.io.*;
// A class to represent a student.
class Student {
int rollno;
String name;
String address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString(){
return this.rollno + " " + this.name +
" " + this.address;
}
}
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of rollno
public int compare(Student a, Student b) {
return a.rollno - b.rollno;
}
}
class Sortbyname implements Comparator<Student> {
// Used for sorting in ascending order of name
public int compare(Student a, Student b) {
return a.name.compareTo(b.name);
}
}
// Driver class
class Main {
public static void main (String[] args) {
ArrayList<Student> ar = new ArrayList<Student>();
//here I have thousand student are inserted into
//simple collection.
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));
System.out.println("Unsorted");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
//collection sorted by rollno
Collections.sort(ar, new Sortbyroll());
System.out.println("\nSorted by rollno");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
//sort by Name
Collections.sort(ar, new Sortbyname());
System.out.println("\nSorted by name");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
}
}
First of all your question is incomplete and misleading. It does not describes the requirement properly. But overall what I assume
You want Google like (?) suggester in your text box
It does not tell any specific things. What about your front end ? How about your data ?
Any way I think you just wanted to have a console like application where you will give partial String as input and your method will guess the Rest of String as an assumption from your dummy data. Am I right ?
If that is the thing you were looking for then I just sketched a demo code below
static List<String> query(String queryStr, List<Student> list) {
List<String> suggestion = new ArrayList<>();
list.forEach(std -> {
if (isMatched(queryStr, String.valueOf(std.getRoll()))) {
suggestion.add(String.valueOf(std.getRoll()));
}
if (isMatched(queryStr, std.getName())) {
suggestion.add(std.getName());
}
if (isMatched(queryStr, std.getAddress())) {
suggestion.add(std.getAddress());
}
});
return suggestion;
}
private static boolean isMatched(String query, String text) {
return text.toLowerCase().contains(query.toLowerCase());
}
And what does this code do ? It actually takes the Partial String that the user input so far and your List<Student> as parameters. Then it iterates over the list and matches for all field for partial match. If any field matches the query it add that value in the suggestion list. In the main you can do like this :
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(101, "Abc ghi", "USA"));
list.add(new Student(102, "DEF", "UST"));
list.add(new Student(103, "Ghi ab", "DSjkD"));
list.add(new Student(104, "jKL ut", "USN"));
list.add(new Student(105, "MNP", "TSA101"));
list.add(new Student(106, "UTC ABC", "ESA"));
List<String> sugg = query("01", list);
sugg.forEach(System.out::println);
}
and you will find the console printed like :
101
TSA101
Does it make sense ? it might not be your whole confusing requirements. But I think you got the idea. You can exploit this to address your own requirements. You could further imply your sorting logic or any kind of filters to it. It should not be that tough thing.
But you should be concerned that with large number of collection or complex associated objects this would not suffice. Real world application does not work this straight forward. You might need lot of other things to consider like memory, i/o and execution time.
Good Luck!
Do refer https://github.com/nikcomestotalk/autosuggest/
This implementation is in java based on Patricia trie and Edit distance algorithm.
Some salient features of this application is
Auto correction of keywords
Bucket support for sorting and personalization support.
Filtering support.
Limit support.
Build in http server.
Blazing fast search.
And you all are welcome for feedback
Solr/Lucene/Elastic will not give freedom to choose algorithm and personalization support.
You can use a Trie data structure for autosuggestion implementation and the time complexity would be O(word_length) for insert and search.
Apache commons provides implementation "org.apache.commons.collections4.Trie"
example:
Trie<String, String> trie = new PatriciaTrie<>();
trie.put("abcd", "abcd");
trie.put("abc", "abc");
trie.put("abef", "abef");
SortedMap<String, String> map = trie.prefixMap("ab");
map.forEach((k, v) -> {
System.out.println(k + " " + v);
});

Java - How to use a for each loop to check the different occurrences of a value in a list of objects

Sorry if the title isn't clear, I wasn't sure how to word it. I have an arraylist of objects and within each of these objects I store an integer value referring to a category and one referring to an ID.
I want to find the number of unique combinations of category and IDs that there are.
So at the moment I have
for(Object object: listofObjects){
//For each unique type of object.getID
//For each unique type of object.getCategory
//Add 1 to counter
}
I can't figure out how to do this. Doing things like for(int cat: object.getCategory()) brings up an error.
I can add the values to a new list within the initial for each loop like so,
ArrayList<Integer> aList= new ArrayList<Integer>();
for (Object object : spriteExplore) {
aList.add(object.getCategory());
}
for (int cat : aList) {
testCounter++;
}
but this obviosuly does not take into account uniqueness and also makes it awkward for factoring in the other variable of ID.
I feel like there is probably some easier work around that I am missing. Any advice?
Thanks in advance.
So you list of UserDefine object in ArrayList and you want to find unique Object.Just create set from list.
For e.g Suppose you have
List<Customer> list=new ArrayList<Custeomer>();
list.add(new Customer("A",12));
list.add(new Customer("B",13));
list.add(new Customer("A",12));
now
create set From this list
Set<Customer> set = new HashSet<Customer>(list);
this will have unique Customer
IMP : dont forget to override equals and hashcode method for Customer
Your best approach would be storing the data correctly.
It's possible that you still need to store non-unique items, if that's so - continue using an ArrayList, but in addition, use the following:
Override the hashcode & equels function as shown in this link:
What issues should be considered when overriding equals and hashCode in Java?
Then, use a Set (HashSet would probably be enough for you) to store all your objects. This data structure will disregard elements which are not unique to elements already inside the set.
Then, all you need to do is query the size of the set, and that gives you the amount of unique elements in the list.
I don't know any library that does this automatically, but you can do it manually using sets. Sets will retain only unique object so if you try to add the same value twice it will only keep one reference.
Set<Integer> categories = new HashSet<Integer>();
Set<Integer> ids= new HashSet<Integer>();
for (Object object : listofObjects) {
categories.add(object.getCategory());
ids.add(object.getID());
}
Then you get the number of unique categories / ids by doing
categories.size()
ids.size()
And all your unique values are stored in the sets if you want to use them.
I would look into using a (Hash)Map<Integer, Integer>. Then just have 1 foreach loop, checking to see if the value of Map<object.getId(), object.getCategory()> is null by checking if map.get(object.getId()) is null - if it is, then this pair does not exist yet, so add this pair into the map by using map.put(object.getId(), object.getCategory()). If not, do nothing. Then at the end, to find the number of unique pairs you can just use map.size()
Hope this helps
Map<Integer,List<Integer>> uniqueCombinations = new HashMap<Integer,List<Integer>>();
for (Object object : listofObjects) {
if(uniqueCombinations.get(object.getCategoryId())==null) {
uniqueCombinations.put(object.getCategoryId(), new LinkedList<Integer>);
}
uniqueCombinations.get(object.getCategoryId()).add(object.getId());
}
return uniqueCombinations.size()
I believe you want unique combinations of both category and id, right?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SO {
class MyObject{
private int id;
private int category;
private String name;
private MyObject(int id, int category,String name) {
super();
this.id = id;
this.category = category;
this.name = name;
}
protected int getId() {
return id;
}
protected int getCategory() {
return category;
}
#Override
public String toString() {
return "MyObject [id=" + id + ", category=" + category + ", name=" + name + "]";
}
}
public static void main(String[] args) {
SO so = new SO();
List<Object> listofObjects = new ArrayList<Object>();
listofObjects.add(so.new MyObject(1,1,"One"));
listofObjects.add(so.new MyObject(1,1,"Two"));
listofObjects.add(so.new MyObject(1,2,"Three"));
Map<String,List<MyObject>> combinations = new HashMap<String,List<MyObject>>();
for(Object object: listofObjects ){
//For each unique type of object.getID
//For each unique type of object.getCategory
//Add 1 to counter
if (object instanceof MyObject){
MyObject obj = (MyObject)object;
String unique = obj.id+"-"+obj.category;
if (combinations.get(unique) == null){
combinations.put(unique, new ArrayList<MyObject>());
}
combinations.get(unique).add(obj);
}
}
System.out.println(combinations);
//counts
for(Entry<String,List<MyObject>> entry:combinations.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue().size());
}
}
}
Use the Hashmap to save occurence. Dont forget to implement hashcode und equals Methods. You can generate them if you work with Eclipse IDE.
public static void main(String[] args) {
List<MyObject> myObjects = Arrays.asList(new MyObject(1, 2), new MyObject(2, 3), new MyObject(3, 4), new MyObject(3, 4));
Map<MyObject, Integer> map = new HashMap<>();
for (MyObject myObject : myObjects) {
Integer counter = map.get(myObject);
if(counter == null){
counter = 1;
} else {
counter = counter + 1;
}
map.put(myObject, counter);
}
long uniqueness = 0;
for(Integer i : map.values()){
if(i == 1){
++uniqueness;
}
}
System.out.println(uniqueness);
}
The last part can be replaced by this one line expression if you are working with Java 8:
long uniqueness = map.values().stream().filter(i -> i == 1).count();

Getting values from one Array List using objects of another array list java

I have 3 ArrayLists.
Students (ID, Name, Program)
Courses (ID, Name, Credit Hours)
StudentCourses (StudentId, CourseID)
I am searching from StudentCourses by passing the StudentID and getting the courses registered with his/her name.
My StudentCourse ArrayLIst has objects like this
49 (Student ID)
CS233(Course ID)
49 (Student ID)
CS231(Course ID)
When a user searches for a student, say I'm searching for Johnna with her registration number 49.
The result is
Reg ID: 49
Name : Johnna
Program: BSCS
Courses Registered:
CS233
CS231
Which is fine. But, what I really need to do is get the name of the course using the course IDs that appear in the search info of Johnna. The Course ArrayList looks like this:
CS233
OOP
BSCS
CS231
ALgorithms
BSCS
I tried this code but it didn't seem to work. It keeps giving either garbage values or it just prints all Course names until there is a null exception:
if (myStudent == null) {
System.out.print("No Record Was Found");
} else {
System.out.print("Student ID: " + myStudent.getID() + "\nFull Name: " + myStudent.getName() + "\nProgram: " + myStudent.getProgram() +
"\nTotal Credit Hours: " + (Integer.parseInt(myStudent.getTotalCreds())) * 3420 + "Rs" + "\nCourses Registered:\n");
}
for (int i = 0; i < studCourseList.size(); i++) {
if (studCourseList.get(i).getSid().equals(ID)) {
System.out.print("- " + studCourseList.get(i).getCid() + "\n");
for (int j = 0; j < CoursesList.size(); j++) {
if(CoursesList.get(i).getID().equals(studCourseList.get(i).getCid())){
System.out.print("- " + CoursesList.get(i).getName() + "\n");
break;
}
}
}
}
The upper portion is bringing the Student info, the first loop is for the Courses registered against the student ID, and the second loop is not working.
Note that all objects are on different lines.
Well for starters, remove the semicolon after this if statement!
if(CoursesList.get(i).getID().equals(studCourseList.get(i).getCid()))
If that doesn't solve your problem, we're going to need more information about what studCourseList and CoursesList is. My inclination would be to guess that in your second loop you should use j like so:
if (CoursesList.get(j).getID().equals(studCourseList.get(i).getCid()))
But without explicit knowledge of your classes I can't be sure if that is correct.
In your nested for loop you use 'j' as a counter but inside that loop you reference 'i'.
for (int j = 0;j<CoursesList.size(); j++){
if (CoursesList.get(i).getID().equals(studCourseList.get(i).getCid()));
{
System.out.print("- " + CoursesList.get(i).getName() + "\n");
break;
}
It looks like
.equals(studCourseList.get(i).getCid()
should use 'j' as a reference otherwise you are not actually going through the studCourseList and are just comparing the same two items over and over.
I suggest you to use Map in place of List in this situation where Id is treated as key and POJO as its value.
HashMap is more faster than List in search.
Sample code:
class Student {
private String id;
private String name;
private String program;
// getter setter
}
class Course {
private String id;
private String name;
private int creditHours;
// getter setter
}
class StudentCourses {
private String studentId;
private String courseId;
// getter setter
}
Map<String, Student> students = new HashMap<String, Student>();
Map<String, Course> courses = new HashMap<String, Course>();

Categories

Resources