Athirah Hazira
Athirah Hazira

Reputation: 473

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?

Upvotes: 6

Views: 5223

Answers (9)

Terry Li
Terry Li

Reputation: 17268

This is what I usually did when I was a newbie:

        String name[] = {"Percy","Daniel","Layla"};
        int marks[] = {90, 87, 91};
        String merged[] = new String[name.length];
        for (int i=0; i< name.length; i++) {
            merged[i] = name[i]+"=="+marks[i];
        }
        Arrays.sort(merged);
        for(int i = 0; i < merged.length; i++) {
            System.out.println( (i+1) + ". "+ merged[i].split("==")[0] + "\t\t" + merged[i].split("==")[1]);
        }

Upvotes: 0

Brian Rogers
Brian Rogers

Reputation: 129707

Your problem can solved easily using a Map. A Map is a class which can be used to store linked pairs of data, where each pair has a "key" and a "value". Once stored in the map, you can quickly look up any value if you have its corresponding key. There is also a way to iterate over, or list out, all the keys in the map.

Here is a simple program showing how to use a Map to solve the problem:

import java.util.*;

public class Example
{
    public static void main(String[] args)
    {
        String[] name = new String[] {"Percy", "Daniel", "Layla"};
        int[] marks = new int[] {90, 87, 91};

        // First create a TreeMap to hold the data.  A TreeMap is a special
        // kind of Map which keeps the keys in sorted order for you.
        // In this TreeMap, the keys will be Strings and the values
        // will be Integers.
        TreeMap<String, Integer> map = new TreeMap<String, Integer>();

        // Next, link each name in the names array to the corresponding mark
        // by putting them in the TreeMap.  Each name becomes a key
        // in the map, and each mark is a value.
        for (int i = 0; i < name.length; i++)
        {
            map.put(name[i], marks[i]);
        }

        // Now we can iterate over the keys in the map, and for each key
        // retrieve the corresponding value.  The TreeMap guarantees
        // the keys will be in sorted order.
        for (String key : map.keySet())
        {
            System.out.println(key + "\t" + map.get(key));
        }
    }
}

Here is the output:

Daniel  87
Layla   91
Percy   90

Upvotes: 1

Vikrant Goel
Vikrant Goel

Reputation: 654

Assuming that you have Unique names, you can use HashMap to have a name-marks pair. Map returns its keyset(name in this case) sorted.

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

if (name.length!=marks.length){
    System.exit(0);
}
HashMap<String, Integer> hm = new HashMap<String, Integer>();
for(int i=0;i<name.length;i++){
    hm.put(name[i], marks[i]);
}

ArrayList<String> keys = new ArrayList<String>(hm.keySet()); //for descending order
for(int i=keys.size()-1, j=0; i>=0;j++,i--){
    System.out.println((j+1)+". "+keys.get(i)+"\t\t"+hm.get(keys.get(i)));
}

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

There's no standard solution. Try this

static void sort(String[] name, int[] marks) {
    for (int i = 0; i < name.length; i++) {
        for (int j = i; j > 0 && (name[j - 1]).compareTo(name[j]) > 0; j--) {
            swap(name, j, j - 1);
            swap(marks, j, j - 1);
        }
    }
}

private static void swap(String[] x, int a, int b) {
    String t = x[a];
    x[a] = x[b];
    x[b] = t;
}

private static void swap(int[] x, int a, int b) {
    int t = x[a];
    x[a] = x[b];
    x[b] = t;
}

This is a modified version of insertion sort algorithm from Arrays.sort

Upvotes: 1

Jhanvi
Jhanvi

Reputation: 5139

Try something like this:

        String name[] = {"Percy", "Daniel", "Layla"};
        int marks[] = {90, 87, 91};
        ArrayList<String> arrayList = new ArrayList<String>();
        System.out.println("Before Sorting..");
        for (int i = 0; i < name.length; i++) {
            arrayList.add(name[i] + " " + marks[i]);
            //Before Sorting
            System.out.println(i + 1 + " " + name[i] + " " + marks[i]);
        }

        Collections.sort(arrayList);
        //After Sorting
        System.out.println("After Sorting..");
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(i + 1 + " " + arrayList.get(i));
        }

Upvotes: 1

sdanzig
sdanzig

Reputation: 4500

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.

Upvotes: 2

regulus
regulus

Reputation: 1622

Well merging a String array and an integer array does not make sense. Unless performance is a priority issue for you, implementing the solution in object oriented ways is much better. I would create a class that holds name and mark. So there will be an instance of this class for each name and mark pair. Then I would implement Comparable interface which makes this class sortable.

class Grade implements Comparable<Grade>{
    String name;
    int mark;

    public int compareTo(Grade o) {
        return name.compareTo(o.name);
    }
}

Upvotes: 0

Augustus Thoo
Augustus Thoo

Reputation: 492

Create a new Comparable class NameScore

public class NameScore implements Comparable<NameScore> {

private final String name;
private final int marks;

public NameScore(String name, int marks) {
    this.name = name;
    this.marks = marks;
}

@Override
public int compareTo(NameScore other) {
    // compare by name
    return this.name.compareTo(other.name);

    // compare by (ascending) marks 
    //return this.marks - other.marks;
}

@Override
public String toString() {
    return "" + name + " (" + marks + ")";
}
}

Here is how to use NameScore to solve your question:

public static void main(String[] args) {
    String name[] = {"Percy", "Daniel", "Layla"};
    int marks[] = {90, 87, 91};

    List<NameScore> list = new LinkedList<NameScore>();
    for (int i = 0; i < marks.length; i++) {
        NameScore element = new NameScore(name[i], marks[i]);
        list.add(element);
    }

    System.out.println("BEFORE : "+list);

    Collections.sort(list);

    System.out.println(" AFTER : "+list);
}

Upvotes: 0

Arvind
Arvind

Reputation: 199

It can be done using two ways

  1. If the sorting in only by name, add the name and marks to TreeMap as key and value, which sorts automatically.
  2. If needs to be sorted by both, create class with these variables and implement the comparable interface.

Upvotes: 0

Related Questions