Java Array Sort sortTable(String[][] data, int index)

Here you can find the source of sortTable(String[][] data, int index)

Description

sort Table

License

Apache License

Declaration

public static String[][] sortTable(String[][] data, int index) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;

import java.util.HashMap;

import java.util.List;
import java.util.Map;

public class Main {

    public static String[][] sortTable(String[][] data, int index) {
        Map<String, String[]> map = new HashMap<String, String[]>();
        List<String> listKeys = new ArrayList<String>();

        for (int i = 0; i < data.length; i++) {
            String[] row = data[i];
            String key = row[index];
            map.put(key, row);/*w  w  w .j av a 2s .  c o m*/
            listKeys.add(key);
        }
        Collections.sort(listKeys);
        String[][] result = new String[listKeys.size()][];
        for (int i = 0; i < listKeys.size(); i++) {
            String key = listKeys.get(i);
            result[i] = map.get(key);
        }
        return result;
    }

    public static String[][] sortTable(String[][] data, int index,
            Comparator<String> comparator) {
        Map<String, String[]> map = new HashMap<String, String[]>();
        List<String> listKeys = new ArrayList<String>();

        for (int i = 0; i < data.length; i++) {
            String[] row = data[i];
            String key = row[index];
            map.put(key, row);
            listKeys.add(key);
        }
        Collections.sort(listKeys, comparator);
        String[][] result = new String[listKeys.size()][];
        for (int i = 0; i < listKeys.size(); i++) {
            String key = listKeys.get(i);
            result[i] = map.get(key);
        }
        return result;
    }

    public static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) {
        V valueOld = map.get(key);
        if (valueOld == null) {
            map.put(key, value);
        }
        return map;
    }
}

Related

  1. sortStrings(final String[] strings)
  2. sortStrings(String[] strings)
  3. sortStrings(String[] strings)
  4. sortStrings(String[] strings)
  5. sortSubFiles(String[] p_subFiles)
  6. sortToFXYSumOrder(final double[] coeffs)
  7. sortTwoArrays(A[] firstArray, B[] secondArray)
  8. sortWith(final int[] ary, int[] ary2)
  9. SortWithIndex(double[] arr, Integer[] i)