php's array_multisort function equivalent in java - java

I was looking for an equivalent of *php's array_multisort* in java.
//array 1
ar1 = array(10, 100, 100, 0);
//array 2
ar2 = array(1, 3, 2, 4);
//calling the function
//this will sort the array at first based one the first array and then based on the
//second array so these two array are related
array_multisort(ar1, ar2);
//resultant 1st array
array(4) {
[0]=> int(0)
[1]=> int(10)
[2]=> int(100)
[3]=> int(100)
}
//resultant 2nd array
//this array has been sorted based on the first array at first
array(4) {
[0]=> int(4) // this is associative element of 0 in the first array
[1]=> int(1) //this is associative element of 10 in the first array
[2]=> int(2) //this is associative element of 1st 100 from the last in the first array
//as there are two 100's , and last one's associative value in the second
//array is smaller it will come first
[3]=> int(3)
}
how can i achieve this result using something built-in , i know how to implement it using custom code.
N.B. *Please visit this link before answering the question as that explains how the function should work*

This is a bit more complicated and can't be done without the Java standard API. So I have recycled a quicksort implementation and made it work for multiple arrays. Basically it swaps the elements when they are swapped by the partitioning of quicksort.
Here you go:
/**
* Multi-sorts the given arrays with the quicksort algorithm. It assumes that
* all arrays have the same sizes and it sorts on the first dimension of these
* arrays. If the given arrays are null or empty, it will do nothing, if just
* a single array was passed it will sort it via {#link Arrays} sort;
*/
public static void multiQuickSort(int[]... arrays) {
multiQuickSort(0, arrays);
}
/**
* Multi-sorts the given arrays with the quicksort algorithm. It assumes that
* all arrays have the same sizes and it sorts on the given dimension index
* (starts with 0) of these arrays. If the given arrays are null or empty, it
* will do nothing, if just a single array was passed it will sort it via
* {#link Arrays} sort;
*/
public static void multiQuickSort(int sortDimension, int[]... arrays) {
// check if the lengths are equal, break if everything is empty
if (arrays == null || arrays.length == 0) {
return;
}
// if the array only has a single dimension, sort it and return
if (arrays.length == 1) {
Arrays.sort(arrays[0]);
return;
}
// also return if the sort dimension is not in our array range
if (sortDimension < 0 || sortDimension >= arrays.length) {
return;
}
// check sizes
int firstArrayLength = arrays[0].length;
for (int i = 1; i < arrays.length; i++) {
if (arrays[i] == null || firstArrayLength != arrays[i].length)
return;
}
multiQuickSort(arrays, 0, firstArrayLength, sortDimension);
}
/**
* Internal multi quicksort, doing the real algorithm.
*/
private static void multiQuickSort(int[][] a, int offset, int length,
int indexToSort) {
if (offset < length) {
int pivot = multiPartition(a, offset, length, indexToSort);
multiQuickSort(a, offset, pivot, indexToSort);
multiQuickSort(a, pivot + 1, length, indexToSort);
}
}
/**
* Partitions the given array in-place and uses the end element as pivot,
* everything less than the pivot will be placed left and everything greater
* will be placed right of the pivot. It returns the index of the pivot
* element after partitioning. This is a multi way partitioning algorithm, you
* have to provide a partition array index to know which is the array that
* needs to be partitioned. The swap operations are applied on the other
* elements as well.
*/
private static int multiPartition(int[][] array, int start, int end,
int partitionArrayIndex) {
final int ending = end - 1;
final int x = array[partitionArrayIndex][ending];
int i = start - 1;
for (int j = start; j < ending; j++) {
if (array[partitionArrayIndex][j] <= x) {
i++;
for (int arrayIndex = 0; arrayIndex < array.length; arrayIndex++) {
swap(array[arrayIndex], i, j);
}
}
}
i++;
for (int arrayIndex = 0; arrayIndex < array.length; arrayIndex++) {
swap(array[arrayIndex], i, ending);
}
return i;
}
/**
* Swaps the given indices x with y in the array.
*/
public static void swap(int[] array, int x, int y) {
int tmpIndex = array[x];
array[x] = array[y];
array[y] = tmpIndex;
}
Done a little testcase to test your input from the question:
#Test
public void testMultiQuickSort() {
int[] first = new int[] { 10, 100, 100, 0 };
int[] second = new int[] { 1, 3, 2, 4 };
int[] resFirst = new int[] { 0, 10, 100, 100 };
int[] resSecond = new int[] { 4, 1, 2, 3 };
ArrayUtils.multiQuickSort(first, second);
for (int i = 0; i < first.length; i++) {
assertEquals(resFirst[i], first[i]);
assertEquals(resSecond[i], second[i]);
}
}
Seems to work ;)
BTW if you need it for an arbitrary object type, just leave a comment.

A multi-dimensional array is just an array of arrays, so iterate over the individual arrays and sort them:
int[][] marr = // your multi-dimensional array here
for (int[] arr : marr) {
Arrays.sort(arr);
}
And if, for whatever possible reason, you only want to sort the first array in the second dimension, this will do:
Arrays.sort(marr[0]);
Argh, now I understand what you want. If your elements (at least those of the first array) are unique, you can do it via a SortedMap:
if(arr1.length!=arr2.length)throw new IllegalArgumentException();
SortedMap<Integer,Integer> map = new TreeMap<Integer, Integer>();
for (int i = 0; i < arr1.length; i++) {
map.put(arr1[i],arr2[i]);
}
int ct = 0;
for (Entry<Integer, Integer> entry : map.entrySet()) {
arr1[ct]=entry.getKey();arr2[ct]=entry.getValue();
ct++;
}

It's look like that there is not any built-in library function / class for this purpose in Java .
If you are also facing this problem like me , so far Thomas's answer about the custom code can help you.

implements Comparator or using algorithm bubble sort
Arrays.sort(stringArray); it will sort only one array

Maybe the following code will help you.
You should use Arrays.sort()
Example:
import java.util.Arrays;
String [] stringArray = {"ab", "aB", "c", "0", "2", "1Ad", "a10"};
//order Ascending
Arrays.sort(stringArray);
//Descending
Arrays.sort(stringArray, Collections.reverseOrder());

Related

Minimum number of Groups needed to convert the given Array to another Array

I have a given array with unique values say [1,4,3,2] and another desired array [1,2,4,3]
I want to cut this input array into a minimum number of pieces so I can convert that to the desired array by just re-arranging the cut pieces.
So for the input array [1,4,3,2] I can cut into pieces (1), (4,3), (2) and re-arrange like (1),(2),(4,3) to get the desired array [1,2,4,3]
Constraints:
Array values are unique.
The size of both arrays is the same and can be up to 1000.
Values in arrays are integers
So the answer is 3 pieces for this example.
Here is what I have tried:
public int process(int[] inp, int[] desired) {
int ans = 0;
for (int i = 0; i < inp.length; i++) {
if (inp[i] != desired[i]) ans++;
}
return ans;
}
My approach is not a correct one, as I am finding elements at each index to count the mismatches. What is the correct approach for solving this problem?
Since all elements in the given arrays are unique, we can store index the positions of elements in one of these arrays by generating a map of type Map<Integer,Integer> associating an array element (Key) with its index (Value).
Then iterate over the second array, searching for identical chunks.
For that, we need to maintain a variable prevIndex that would store the index occupied by the previous element in the first array. While iterating, we would need to check each next index in the first array (corresponding to the next element in the first array). If the next index differs from the previous only by one - the next element is proved to be a part of a chunk with identical order, and we're just incrementing prevIndex. Otherwise, increment the count of chunks.
public static int process(int[] arr1, int[] arr2) {
Map<Integer, Integer> indexByValue = mapIndices(arr2);
int count = 1;
int prevIndex = indexByValue.get(arr1[0]);
for (int i = 1; i < arr1.length; i++) {
int nextIndex = indexByValue.get(arr1[i]);
if (nextIndex == prevIndex + 1) {
prevIndex++;
} else {
prevIndex = nextIndex;
count++;
}
}
return count;
}
public static Map<Integer, Integer> mapIndices(int[] arr) {
return IntStream.range(0, arr.length)
.boxed()
.collect(Collectors.toMap(
i -> arr[i],
Function.identity()
));
}
main()
public static void main(String[] args) {
System.out.println(process(new int[]{1, 4, 3, 2}, new int[]{1, 2, 4, 3}));
}
Output:
3

How to merge and print two sorted arrays of ints

I'm trying to create a method that takes in two sorted int arrays and returns a new array that merges and resorts the two lists without using a sort function. I'm having trouble within my loop and I'm not sure how to fix it.
I'm currently getting the errors:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at pack8.Assignment8Code.merge(Assignment8Code.java:20)
at pack8.Assignment8Code.main(Assignment8Code.java:39)
Here is the code:
public class Assignment8Code
{
public static int[] merge(int[] arr1, int[] arr2)
{
//Create the first two arrays with testing numbers
arr1 = new int[5];
arr2 = new int[3];
//Create a new array that will fit the length of the two given arrays
int[] sortedArray = new int[(arr1.length + arr2.length)];
//Create starting index values to check all arrays and merge
int index1 = 0;
int index2 = 0;
//Test to see if the given arrays are populated
while(index1 < arr1.length || index2 < arr2.length)
{
//Check to see which array starts with the higher number
if(arr1[index1] < arr2[index2])
{
sortedArray[index1] = arr1[index1];
index1++;
}
else
{
sortedArray[index2] = arr2[index2];
index2++;
}
}
return sortedArray;
}
}
There are multiple problems in your code:
you should use a separate method for testing, assigning arr1 and arr2 in the merge method defeats its purpose.
you must use a separate index for the destination array.
you should stop comparing elements when you reach the end of either array
you should deal with remaining elements separately.
Here is a corrected version of the merge method:
public class Assignment8Code
{
public static int[] merge(int[] arr1, int[] arr2)
{
// Allocate a new array that will fit the length of the two given arrays
int[] sortedArray = new int[(arr1.length + arr2.length)];
int index1 = 0;
int index2 = 0;
int index3 = 0;
// Merge the sorted arrays
while (index1 < arr1.length && index2 < arr2.length)
{
//Check to see which array starts with the higher number
if (arr1[index1] <= arr2[index2])
{
sortedArray[index3++] = arr1[index1++];
}
else
{
sortedArray[index3++] = arr2[index2++];
}
}
// Append the remaining elements
while (index1 < arr1.length)
{
sortedArray[index3++] = arr1[index1++];
}
while (index2 < arr2.length)
{
sortedArray[index3++] = arr2[index2++];
}
return sortedArray;
}
}
Note that this approach is quite inefficient as it allocates a new array for each merge. Implementing mergesort this way for large arrays would allocating a substantial amount of mmemory (log2(N) * N integers) causing unnecessary stress on the garbage collector. Using a single temporary array for the whole mergesort would be much more efficient but require a different merge method.

iterating through multidimensional ArrayList

I am confused regarding iterating through a multidimensional ArrayList .
I saw some topics about it and they seem complicated. in specific the accepted
answer here:
How to iterate through two dimensional ArrayList using iterator?
can it be as in this method? which iterates through the arrayList and copy the value to an array:
private void reassembleArray(int[] array, ArrayList<ArrayList<Integer>> buckets) {
Iterator<ArrayList<Integer>> it = buckets.iterator();
int i = 0;
while (it.hasNext()) {
ArrayList<Integer> intList = it.next();
Iterator<Integer> itInteger = intList.iterator();
while (itInteger.hasNext()) {
array[i] = itInteger.next();
i++;
}
}
}
are there any dangers or side effects for using this simple form?
this is the complete program which is an implementation of a sort algorithm called radix sort.
import java.util.ArrayList;
import java.util.Iterator;
/**
* Radix sort implementation
*/
public class RadixSort {
/**
* Runs the program
*/
public static void main(String[] args) {
int[] array = {315, 418, 591, 260, 533, 58, 976, 938,};
System.out.println("Radix sort implementation");
printArray(array);
sort(array, 3); // 3 is the maximun number of digits in all array elements to sort
printArray(array);
}
/*
* sort array of integers using radix sort algorithm
* #param array The array
* #param n the maximum number of digits in array elements
*/
private void sort(int[] array, int n) {
int digitNumber = 0;
while (digitNumber < n) {
ArrayList<ArrayList<Integer>> buckets = initBuckets();
// store each element in the bucket corresponding to the (digitNumber + 1)th
// digit of that element
for (int i = 0; i < array.length; i++) {
int value = array[i];
int bucket = (value / (int) (Math.pow(10, digitNumber))) % 10;
buckets.get(bucket).add(value);
}
reassembleArray(array, buckets);
digitNumber++;
}
}
/*
* Initialize buckets ArrayList
* #return The buckets ArrayList
*/
private ArrayList<ArrayList<Integer>> initBuckets() {
ArrayList<ArrayList<Integer>> buckets = new ArrayList<ArrayList<Integer>>();
// a bucket for each digit from 0 to 9
for(int i = 0; i < 10; i++) {
buckets.add(new ArrayList<Integer>());
}
return buckets;
}
/*
* Reassemble the array
* #param array The array
* #param buckets The buckets
*/
private void reassembleArray(int[] array,
ArrayList<ArrayList<Integer>> buckets) {
Iterator<ArrayList<Integer>> it = buckets.iterator();
int i = 0;
while (it.hasNext()) {
ArrayList<Integer> intList = it.next();
Iterator<Integer> itInteger = intList.iterator();
while (itInteger.hasNext()) {
array[i] = itInteger.next();
i++;
}
}
}
/*
* Prints an array of integers on a single line
* #param array The array
*/
private void printArray(int[] array) {
System.out.print("array: {");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ((i == array.length - 1) ?"" : ", "));
}
System.out.println("}");
}
}
The algorithm simply requires sorting the collection through a number of steps,
first sort the collection according to the first digit to the right and have all the elements that in buckest of 0 - 9 according to that last digit while maintaining the initial order of the collection, then starting from bucket 0 reassemle the collection again and proceed to sorting according to the next digit to the left and so on.
the program does work and sorts the collection fine.
I bet the output you get is not the same one as you expect since the following line results in:
array[i] = itInteger.next();
Type mismatch: cannot convert from Integer to int[]
As far as I understand you want to convert List<List<Integer>> structure to the array of the same type. You also need to map Integer to int using Stream::mapToInt:
int array[][] = new int[buckets.size()][];
IntStream.range(0, buckets.size())
.forEach(i -> array[i] = buckets.get(i)
.stream()
.mapToInt(j -> j.intValue())
.toArray());
System.out.println(Arrays.deepToString(array)); // Prints the very same output
Also, you don't need to use Iterator, however if you insist on it:
int outerIndex = 0;
while (outerIterator.hasNext()) {
List<Integer> list = outerIterator.next();
Iterator<Integer> innerIterator = list.iterator();
array[outerIndex] = new int[list.size()];
int innerIndex = 0;
while (innerIterator.hasNext()) {
array[outerIndex][innerIndex] = innerIterator.next().intValue();
innerIndex++;
}
outerIndex++;
}
Are there any dangers or side effects for using this simple form?
Yes, both of the solutions are since they don't amend the original resource of input nor affect another resource.
Your code will be clearer if you use enhanced for loops instead of iterators:
int i = 0;
for (List<Integer> intList : buckets) {
for (int value : intList) {
arr[i++] = value;
}
}

Find greatest of two arrays, storing result in a third array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How do I sort into two arrays and storing in another array in java?
public class SortingDemo {
public static void main(String[] args) {
int[] num1 = new int[ ] {5,6,2,8};
int [] num2 = new int[] {1,4,10,7};
merge(num1, num2);
}
public static int[] merge(int [] num1,int [] num2) {
int num1_size = num1.length;
int num2_size = num2.length;
for (int i = 0; i < num1.length; i++) {
// System.out.println(num1[i]);
for (int j = 0; j < num2.length; j++) {
if (num1[i] > num2[j]) {
}
}
}
}
}
I suppose you are not particular about merge sorting. You just need to make a third array and combine the result into 3rd array and sort it.
I that case just make a new array like
int[] num3 = new int[num1.length + num2.length];
System.arraycopy(num1, 0, num3, 0, num1.length);
System.arraycopy(num2, 0, num3, num1.length, num2.length);
and sort num3 with any sorting algorithm.
But if you are particular about merge sort
Merge sort works as follows
Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining. This will be the sorted list.
Final program would be like
import java.util.Arrays;
public class SortingDemo {
public static void main(String[] args) {
int[] num1 = new int[] { 5, 6, 2, 8 };
int[] num2 = new int[] { 1, 4, 10, 7 };
// Combine both into thrid array
int[] num3 = new int[num1.length + num2.length];
System.arraycopy(num1, 0, num3, 0, num1.length);
System.arraycopy(num2, 0, num3, num1.length, num2.length);
// Sort third array
mergeSort(num3);
System.out.println(Arrays.toString(num3));
// Largest number of two array
System.out.println("Largest : " + num3[num3.length - 1]);
}
public static int[] mergeSort(int[] arrayData) {
if (arrayData.length <= 1) {
return arrayData;
}
int[] first = new int[arrayData.length / 2];
int[] second = new int[arrayData.length - first.length];
System.arraycopy(arrayData, 0, first, 0, first.length);
System.arraycopy(arrayData, first.length, second, 0, second.length);
mergeSort(first);
mergeSort(second);
merge(first, second, arrayData);
return arrayData;
}
private static void merge(int[] first, int[] second, int[] result) {
int iFirst = 0;
int iSecond = 0;
int j = 0;
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
result[j] = first[iFirst];
iFirst++;
} else {
result[j] = second[iSecond];
iSecond++;
}
j++;
}
System.arraycopy(first, iFirst, result, j, first.length - iFirst);
System.arraycopy(second, iSecond, result, j, second.length - iSecond);
}
}
Explanation as per comment.
You have two arrays of 4 elements each. { 5, 6, 2, 8 } and { 1, 4, 10, 7 }. The requirement is to create a new array combining these arrays and sort the newly created array it. So not first ne declare a new array. The size of it will be the length of array 1 + length of array 2. So we create array
int[] num3 = new int[num1.length + num2.length];
Now we need to copy values from both arrays to new array. So usual practice is to use System.arraycopy method. The arguments lists are (source array, initial position to copy from source, target array, position to copy on target, total number of elements to copy). So we'll do like
System.arraycopy(num1, 0, num3, 0, num1.length);
So first it copies from num1 starting at 0th index to the new array, num3, strating from 0th index and all elements from num1. Its equvalent to writing num3[0] = num1[0]; num3[1] = num1[1]; etc up to length of num1 like num3[3] = num1[3]. (i.e length is for so index 0 to 4).
System.arraycopy(num2, 0, num3, num1.length, num2.length);
So second time when we copy we already have values in num3 until 3rd index. So we need to start at 4th index i.e. num3[4] = num2[0]. This is why we set the 3rd argument to num1.length. Rest is similar to first copy.
So now we have a new array with combined values from num1 and num2. Second requirement is to sort it. If you dont want to write any special sorting algorithm you could just use standard sort provided by Arrays class. Like
Arrays.sort(num3);
This will sort the new combined array. Alternatively we could wirte your own sorting. Then we could do any kind of sorting. Say bubble sort or merge sort or quick sort or anything. You can learn about all these algorithms from http://www.sorting-algorithms.com/ or with examples from http://thilinasameera.wordpress.com/2011/06/01/sorting-algorithms-sample-codes-on-java-c-and-matlab/
Since the comments were about merge sorting i just chose merge sort. The idea or merge sort is split the array into two sorted array and then merge this into a new array in sorted order. So in this case first we split the num3 in to half. Then split each into half again and again until the size of array is 1 via a recursive call. This is done in the first part of method mergeSort() This means {5,6,2,8,1,4,10,7} will now be come {5},{6},{2},{8},{1},{4},{10},{7}. The idea here is if an array has only 1 element then that can be considered sorted. So now we have 8 arrays. Now we need to merge these in a sorted fashion taking 2 array at a time. This is what merge() method does.
So first i'll take {5} and {6} and merge to one in sorted way {5,6}. then will merge {2} and {8} to {2,8} and so on to make 4 arrays with 2 elements each. {5,6}, {2,8}, {1,4}, {7,10}. Now repeate the process again with this 4 arrays and so on until we get one array. And that will be sorted.
Hope this helps. Please ask if you have more questions.
Probably, you should do something like this.
public static void main(String[] a)
{
int[] num1= new int[] {5,6,2,8};
int[] num2= new int[] {1,4,10,7};
System.out.println(getMax(num1, num2));
}
private static int getMax(int[] a, int[] b)
{
int max = Integer.MIN_VALUE;
for (int val : a)
{
if (val > max)
max = val;
}
for (int val : b)
{
if (val > max)
max = val;
}
return max;
}
You want to sort the arrays and merge them to get a sorted array?
public static void main(String[] a) {
int[] num1= new int[] {5,6,2,8};
int[] num2= new int[] {1,4,10,7};
sortInPlace(num1);
sortInPlace(num2);
int[] result = merge(num1, num2);
}
Implement the sortInPlace and merge methods.

find longest linked lists in an array of linked lists

I have an array of linked lists (an adjacency list) most of the lengths of the linked lists are 4 but there are some that will randomly have more than that. My goal is to go through the array and find the ones that are more than length 4 (thats the easy part) then add the index's to an array so something like
for (int i = 0; i < 1000; i++){
if(sWorld[i].length > 4)
//add i to an array
// then sort the array
couldnt really figure out how to do this. i tried to add to a inked list then linked list toArray() but then it was messing up. i just dont really know how to add the 'i' point in my sWorld array to say the first position in the new array im going to use for the ones that are grater than size 4.
Any help would be much appreciated!
EDITED TO CLARIFY A BIT
i need the indexes of the the locations that are size > 4, but then i want to know which of those indexes that i get have the greatest size. Maybe i wasnt 100% clear in my op, but basically im trying to find which of the 1000 indexes in the array have the most connections (the longest linked list) make sense?
I want to know the top 10 connected indexes of the array (aka which 10 have the greatest size of linked list)
You can use an ArrayList to store the indexes:
List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++){
if (sWorld[i].length > 4) {
//add i to a list (not an array yet)
indexes.add(i);
}
...
}
// then sort the list
// not necessary, as indexes are inserted in the right order, but if you must...
// Collections.sort(indexes);
// and, if you need an array instead of a list
Integer[] indexesArray = indexes.toArray(new Integer[indexes.size()]);
A List, or an ArrayList, work as variable-length arrays. Though not as efficiently as an actual array.
As seen above, there is no need to sort the array later, but, if you must, you can use Collections.sort().
Also, if you must have an int[] instead of an Integer[], please check: How to convert List<Integer> to int[] in Java?
Update:
As you want to know the size and index of the bigger arrays, it's a whole new problem. Below is a working code that deals with it.
Basically, everytime you find an array with size larger than 4, you add a pair (index, size) to the list. This list is then ordered by size, in descending order.
At the end of the main() method, an array is created (int[] topTenIndexes) which contains the indexes of the 10 biggest arrays (the indexes are presented in descending order of it's array's length). The result is -1 when there weren't enough big (length > 4) arrays.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<ArrayIndexAndSize> indexes = new ArrayList<ArrayIndexAndSize>();
int[][] sWorld = {{1},{2,5,5,5,5},{3,6,6,6,6,6}};
for (int i = 0; i < sWorld.length; i++){
if (sWorld[i].length > 4) {
// add a pair (index, size) to the list
indexes.add(new ArrayIndexAndSize(i, sWorld[i].length));
}
//...
}
// then sort the list by array SIZE, in descending order
Collections.sort(indexes);
// Print it!
System.out.println(indexes);
/* output:
"[[Array index: 2; Array size: 6], [Array index: 1; Array size: 5]]"
*/
// Generating an array with the top ten indexes
int[] topTenIndexes = new int[10];
Arrays.fill(topTenIndexes, -1);
for (int i = 0; i < indexes.size() && i < 10; i++) {
topTenIndexes[i] = indexes.get(i).index;
}
// Print it
System.out.println(Arrays.toString(topTenIndexes));
/* output: [2, 1, -1, -1, -1, -1, -1, -1, -1, -1] */
}
public static class ArrayIndexAndSize implements Comparable<ArrayIndexAndSize> {
public int index;
public int size;
public ArrayIndexAndSize(int index, int size) {
this.index = index;
this.size = size;
}
/* Order by size, DESC */
/* This is called by Collections.sort and defines the order of two elements */
public int compareTo(ArrayIndexAndSize another) {
int thisVal = this.size;
int anotherVal = another.size;
return -(thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
#Override
public String toString() {
return "[Array index: "+index+"; Array size: "+size+"]";
}
}
}
If you have an array LinkedList<?>[] sWorld (fill the type you're using in for ?), then do this:
ArrayList<Integer> listOfLists = new ArrayList<>();
for (int i=0; i<sWorld.size(); i++) {
if (sWorld[i].size > 4) {
listOfLists.add(i);
}
}
Comparator<Integer> sizeComparator = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return Integer.compare(sWorld[a].size(), sWorld[b].size());
}
}
Collections.sort(listOfLists, sizeComparator);

Categories

Resources