Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link or merge 2 arrays into 1 and sort them in java

Is it possible to merge two arrays (one-dimensional) which is string and int and sort them? for example:

String name[] = {"Percy", "Daniel, "Layla"};
int marks[] = {90, 87, 91};

Arrays.sort (name);
for(int i = 0; i < name.length; i++)
    System.out.println( (i+1) + ". "+ name[i] + "\t\t" + marks[i]);

if I would like to sort them, I wanted the output to be like this:

// before sorting
1. Percy       90
2. Daniel      87
3. Layla       91

// after sorting
1. Daniel      90
2. Layla       87
3. Percy       91

// the actual output that i wanted
1. Daniel      87
2. Layla       91
3. Percy       90

What would you suggest me to do? How do I link those 2 arrays and sort them according to their names? Or do how do I merge them? Is there any simple method that I can understand? As I was reading everywhere on the net on using comparators, merge and everything but I'm not that clear on it.

i'm new to java. so is there any method for beginners?

like image 343
Athirah Hazira Avatar asked Oct 26 '13 03:10

Athirah Hazira


1 Answers

You ask for a Java class for beginners. There are a lot of examples on the net about comparators, treesets, and everything else in Java. You definitely need to take your time and read everything you see, but many of those examples are crystal clear. If you are trying to learn something, and it isn't working for you, don't spend more time on it. Just Google again, even if it's the 15th or 20th explanation that finally works for you. This is very common. Just don't read past anything until you understand it.

Certainly have a class to store your string that implements Comparable, as @regulus suggests, except use the name instead of the mark :) Store the mark too in the class, for future reference, or if you wish to have it for a secondary comparison (after comparing the names). This will give your elements a natural ordering. As you're creating each object instance, ...

Insert them into an instance of Java's TreeSet. Here's an example of its usage:

import java.util.TreeSet;
import java.util.Iterator;

public class IterateThroughElementsOfTreeSetExample {

  public static void main(String[] args) {

    //create object of TreeSet
    TreeSet tSet = new TreeSet();

    //add elements to TreeSet object
    tSet.add(new Integer("1"));
    tSet.add(new Integer("2"));
    tSet.add(new Integer("3"));

    //get the Iterator
    Iterator itr = tSet.iterator();

    System.out.println("TreeSet contains : ");
    while(itr.hasNext())
      System.out.println(itr.next());
  }
}

It'd be super fast, because it's sorted as you insert keys.

like image 82
sdanzig Avatar answered Oct 13 '22 01:10

sdanzig