1

I wanted to sort the following 2D array:

String[][] rows = {
            {"M","O","N","K","E","Y"},
            {"D","O","N","K","E","Y"},
            {"M","A","K","E"},
            {"M","U","C","K","Y"},
            {"C","O","O","K","Y"},
            };

and i wanted the following result out of that:

A C C D E E E K K K K K M M M N N O O O O U Y Y Y Y

But i don't know how to do that!! I couldn't find any good examples with 2D array sorting.

As you can see i don't want to sort in columns or rows but i just want to sort all the characters in the array. In this way i can count how much of every character is located in the 2D array.

If you know how to count how many of every character there are in a 2D array that would also be a good solution for me.

3
  • 5
    So the result should be a String or a 1D-array or another 2D-array? Commented Jun 2, 2013 at 16:55
  • 1
    Put them all into a single array and then sort them. What have you tried already? Commented Jun 2, 2013 at 17:01
  • 1
    1-D sorting is explained here docs.oracle.com/javase/tutorial/collections/interfaces/… - you just need to figure out how to get from 2D to 1D. Commented Jun 2, 2013 at 17:34

4 Answers 4

2

This will sort the 2D-array into a List object using Collections.sort.

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        String[][] rows = {
                {"M","O","N","K","E","Y"},
                {"D","O","N","K","E","Y"},
                {"M","A","K","E"},
                {"M","U","C","K","Y"},
                {"C","O","O","K","Y"},
            };

        List<String> list = new ArrayList<String>();

        // Add all strings to list.
        for (String[] row : rows) {
            for (String s : row) {
                    list.add(s);
            }
        }

        Collections.sort(list); // Sort the list.
    }
}

You can convert the List to a basic array using:

String[] arr = list.toArray(new String[list.size()]);

To count every character in the array have a look at jlordo's answer.

Sign up to request clarification or add additional context in comments.

Comments

1

I read that you want to count unique strings? Use this:

    Map<String, Integer> counter = new HashMap<>();
    for (String[] row : rows) {
        for (String str : row) {
            if (counter.containsKey(str)) {
                counter.put(str, counter.get(str) + 1);
            } else {
                counter.put(str, 1);
            }
        }
    }
    System.out.println(counter);

If you want the output to be sorted lexicographicaly, use a TreeMap instead of HashMap and consider using Character instead of String if all you have are single characters.

Comments

0

I understood you want a count of unique characters, in a 2 D string array/ each string is 1 char or we consider only first. This code assumes you want "A" count seperate of "a" else make the string upper case as commented out.

If you wanted character in an array of strings (1D) that can be done too. Following is for 2 D as in your question

import java.util.*;
public class ChrCnt  {
    public static void main(String[] args){

        String[][] rows = {
            {"M","O","N","K","E","Y"},
            {"D","O","N","K","E","Y"},
            {"M","A","K","E"},
            {"M","U","C","K","Y"},
            {"C","O","O","K","Y"},
            };
            Map<Character, Integer> cnts = new HashMap<Character, Integer>();
            for(int i =0; i < rows.length; i++){
                for(int j =0; j < rows[i].length; j++){
                    Character c = rows[i][j].charAt(0);//or .toUpperCase().charAt(0);
                    Integer cnt = cnts.get(c);
                    int cc = 0;
                    if(cnt != null){
                        cc = cnt;
                    }
                    cc++;
                    cnts.put(c, cc);

                }
            }
            Set<Character> st = cnts.keySet();
            prnt(rows);
            int sz = st.size();
            Iterator<Character> it = st.iterator();
            System.out.println("------\nCounts\n");
            while(it.hasNext()){
                Character c = it.next();
                System.out.println(c +  " " + cnts.get(c));
            }


    }

    static void prnt(String[][] rows){

        for(int i =0; i < rows.length; i++){
                for(int j =0; j < rows[i].length; j++){
                    System.out.print(rows[i][j]);
                }
                System.out.println();
            }
    }
}

Output

MONKEY

DONKEY

MAKE

MUCKY

COOKY

Counts

U 1

D 1

E 3

A 1

C 2

M 3

N 2

O 4

Y 4

K 5

Comments

0

A way to sort each character from a 2-d array. Will see that by changing the data members of ArrayDatum and how Cmpr is implemented you can sort other objects in different ways so could have Cmpr2, Cmpr3 ....

public class ArrayDatum <T>{
    private int locX; //probably do not need this -> original location but keot it for future use
    private int locY;
    private T data;

    public ArrayDatum(T dat, int x, int y){
        data = dat;
        locX = x;
        locY = y;
    }

    public int getLocationX(){
        return locX;
    }

    public void setLocationX(int x){
        locX = x;
    }

    public int getLocationY(){
        return locY;
    }

    public void setLocationY(int y){
        locY = y;
    }

    public T getData(){
        return data;
    }

    public void setData(T d){
        data = d;
    }

}

//comparator

import java.util.Comparator;

/**
* Comparator for ArrayDatum<String>
* Else not predictable
*/
public class Cmpr  implements Comparator{

    public int compare(Object  c1, Object b1){

        ArrayDatum c = (ArrayDatum )c1;
        ArrayDatum b = (ArrayDatum )b1;
        if(c == null || b == null) return 0;
        return c.getData().toString().compareTo(b.getData().toString());
    }
}    

//test app

import java.util.*;
public class Tst  {
    public static void main(String[] args){

        String[][] rows = {
            {"M","O","N","K","E","Y"},
            {"D","O","N","K","E","Y"},
            {"M","A","K","E"},
            {"M","U","C","K","Y"},
            {"C","O","O","K","Y"},
            };
            prnt(rows);
            List<ArrayDatum> dat = new ArrayList<ArrayDatum>();
            for(int i =0; i < rows.length; i++){
                for(int j =0; j < rows[i].length; j++){
                    ArrayDatum<String> dt = new ArrayDatum<String>(rows[i][j], i, j);
                    dat.add(dt);
                }
            }
            Cmpr cmpr = new Cmpr();
            Collections.sort(dat, cmpr);
            int sz = dat.size();
            System.out.println("------\nsort\n");
            for(int i =0; i < sz; i++){
                System.out.print(dat.get(i).getData() + " " );
            }
            //for(int i =0; i < sz; i++){
            //  ArrayDatum d = dat.get(i);
            //  rows[d.getLocationX()][d.getLocationY()] = d.getData().toString();
            //}
            int loc = 0;

            /*
            lay them into original array again
            for(int i =0; i < rows.length; i++){
                for(int j =0; j < rows[i].length; j++){
                    rows[i][j] = dat.get(loc).getData().toString();
                    loc++;
                }
            }


            prnt(rows);*/


    }

    static void prnt(String[][] rows){

        for(int i =0; i < rows.length; i++){
                for(int j =0; j < rows[i].length; j++){
                    System.out.print(rows[i][j]);
                }
                System.out.println();
            }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.