Reputation: 3031
I have a problem with arrays in java. I have a array:
double[][] tab2 = {{318, 0.0825},
{321, 0.1131},
{309, 0.0283},
{319, 0.0830}};
and I need to change that array to:
double[][] tab2 = {{318, 0.0830},
{321, 0.0283},
{309, 0.1131},
{319, 0.0825}};
This is what i mean. I have four numbers. In this example 318, 321, 309 and 319. Every number is connected with another number, like 318 - 0.0825, 321 - 0.1131, etc. I need change value second values. When number which is connected with the biggest number should be connected with the smaller eg. 321 - 0.1131 should be 321 - 0.0283, 318 - 0.00830 should be 318 - 0.0825. It is possible to do this things?
Upvotes: 0
Views: 169
Reputation: 21429
You can achieve this by:
HashMap<Integer,Double> mapValues = new HashMap<Integer,Double>();
// Insert keys and values into mapValues
Integer[] keys = mapValues.KeySet().toArray(new Integer[]{});
Double[] values = mapValues.Values().toArray(new Double[]{});
Arrays.sort(keys,Collections.reverseOrder());
Arrays.sort(values);
HashMap<Integer,Double> resultMap = new HashMap<Integer,Double>();
for(int i=0; i<keys.length; i++){
resultMap.put(keys[i], values[i]);
}
Upvotes: 0
Reputation: 36611
This will probably not be the most efficient solution, but it will work
double[][] tab2 = {{318, 0.0825},
{321, 0.1131},
{309, 0.0283},
{319, 0.0830}};
List<Double> firstEntries = new ArrayList<Double>( );
List<Double> secondEntries = new ArrayList<Double>( );
for ( double[] doubles : tab2 ) {
firstEntries.add( doubles[ 0 ] );
secondEntries.add( doubles[ 1 ] );
}
Collections.sort( firstEntries );
Collections.sort( secondEntries );
Collections.reverse( secondEntries );
//now the lists contain the entries in the correct order
//if needed, they can be grouped again in an array
for ( int i = 0; i < tab2.length; i++ ) {
double[] doubles = tab2[ i ];
doubles[1] = secondEntries.get( firstEntries.indexOf( doubles[0] ) );
}
Upvotes: 0
Reputation: 2921
It would be easier to do this if the arrays were arranged in transposed form.
double[][] tab3 = {
{318.0, 321.0, 309.0, 319.0},
{0.0830, 0.1131, 0.0283, 0.0830}}
You can then sort the first array (tab3[0]
) in ascending order and then the second array (tab3[1]
) in descending order. Then all of the array indexes will line up and match the largest to the smallest. double[0][0]
will be the biggest and double[1][0]
will be the smallest, matching 309 and 0.1131 together.
double[][] tab3 = {
{309.0, 318.0, 319.0, 321.0},
{0.1131, 0.0830, 0.0830, 0.0283}}
Upvotes: 4
Reputation: 5543
You can use Map
in this case, Specify first number as key and second number as value. Refer below document for more details about Map.
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Upvotes: 1