Question

I have 2 datasets for 2 months with student names and scores.

I need to provide the Feb scores for each student and percent change with his/her feb scores.

Can i do this with Java collection?

Sample Dataset:

name Jan_score Feb_score John 40 80 Mary 61 81 Jim 52 82 Liz - 84 Tim 94 -

output should be like this

(Name: John, Feb_score: 80, percent change: 100)
(Name: Mary, Feb_score: 81, percent change: 32.76)
(Name: Jim, Feb_score: 82, percent change: 57.69)
(Name: Liz, Feb_score: 84, percent change: N/A)
(Name: Tim, Feb_score: -, percent change: N/A)

Was it helpful?

Solution

Create a HashMap as follows,

        HashMap<String, ArrayList<Integer>> studentMap=new HashMap<String, ArrayList<Integer>>();

Key is the name of the student and the value is their list of marks. index 0 in the ArrayList has the january mark for every student , index 1 has feb mark for every student and continues(If you have more).

You can add the entries as below,

    scores=new ArrayList<Integer>();
    scores.add(40);
    scores.add(80);
    studentMap.put("John", scores);

    scores=new ArrayList<Integer>();
    scores.add(61);
    scores.add(81);
    studentMap.put("Mary", scores);

And to display the values,

for(String name : studentMap.keySet())
    {
        ArrayList<Integer> scoreList=studentMap.get(name);

        System.out.println("Name : "+name+"     Jan Score: "+scoreList.get(0)+"     Feb Score : "+scoreList.get(1));
    }

In between you can add your logic for percentage improvement.

OTHER TIPS

You can store each dataset in a Map (key = student Name, Value = score). So there can be a Map for January and another one for February.

To compute Percentage change do the following :

1) Iterate through all elements in February map (Say current student is stu)

2) Search for the score of Student 'stu' in January Map.

3) Compute the percentage change.

There's no built-in Java collection to do this as this sounds too specific. So you need to go ahead and implement this kind of comparison yourself. As Kakarot pointed out, you can start by using two Maps, then implement the comparison yourself.

For this you can use TreeSet and you make another class in a same package and implement "Comparator Interface" for comparing two object and pass it on TreeSet object creation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top