Sorting int array in descending order [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Sort arrays of primitive types in descending order
Java : How to sort an array of floats in reverse order?
How do I reverse an int array in Java?
The following code will sort the array in ascending order :
int a[] = {30,7,9,20};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
I need to sort it in descending order. How do I use Comparator to do this?
Please help.

For primitive array types, you would have to write a reverse sort algorithm:
Alternatively, you can convert your int[] to Integer[] and write a comparator:
public class IntegerComparator implements Comparator<Integer> {
#Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
or use Collections.reverseOrder() since it only works on non-primitive array types.
and finally,
Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());
//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

If it's not a big/long array just mirror it:
for( int i = 0; i < arr.length/2; ++i )
{
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}

Comparator<Integer> comparator = new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);

Guava has a method Ints.asList() for creating a List<Integer> backed by an int[] array. You can use this with Collections.sort to apply the Comparator to the underlying array.
List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());
Note that the latter is a live list backed by the actual array, so it should be pretty efficient.

Related

sorting array of arrays in descending order using arrays.sort function is resulting in errors in java

problem:https://leetcode.com/problems/maximum-units-on-a-truck/
I am supposed to sort array of arrays of size 2(eg. [[1,3],[2,2],[3,1]]) in descending order according to 2nd value of the inner element. i.e for 1st element[1,3]according to value 3. , but my code is resulting in error: no suitable method found for sort().Some Help would be appreciated.
here is my code in java
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, new Comparator<int[][]>() {
public int compare(final int[][] entry1, final int[][] entry2) {
if (entry1[0][0] < entry2[0][0])
return 1;
else return -1;
}
}
);
for (int i = 0; i < boxTypes.length; i++)
System.out.println(boxTypes[i]);
return 0;
}
}
As mentioned in comments, you are sorting by inner element, which is int[], so you need Comparator<int[]>.
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
Arrays.sort(input, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
System.out.println(Arrays.deepToString(input));
}
}
Note return Integer.compare(o2[1], o1[1]);, second parameter is compared to first in order to achieve descending order.
You could also achieve same effect using lambda, to make it shorter and more readable.
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
System.out.println("Initial array - " + Arrays.deepToString(input));
Arrays.sort(input, (o1, o2) -> Integer.compare(o2[1], o1[1]));
System.out.println("Sorted array - " + Arrays.deepToString(input));
}
}
First, you can't use native type in <>, you need to use Integer instead. Then what you need to compare is the inner array Integer[] if I'm not mistaken so your comparator can't work. Here you are just trying to sort 2 arrays of arrays based on the first element of the first array.
Here is what I would do (using stream):
Integer[][] sortedBoxTypes = Arrays.stream(boxTypes).sorted(Comparator.comparing(entry -> entry[1])).toArray(Integer[][]::new);

Sorting an ArrayList of arrays in java

I'd like to know if you know a way to sort an ArrayList of arrays in Java.
I have a function that gives a score between 0 and 1 to a specific array. And I'd like to sort the ArrayList so that arrays having the highest score come first.
public double evaluate(int[] toEvaluate) {
double result = 0.0;
for (int i = 0; i < toEvaluate.length; i++) {
result += table[i][casesMap.get(toEvaluate[i])];
}
return result / toEvaluate.length;
}
Any ideas ?
You should use Collections.sort() together with a custom Comparator:
List<Integer[]> arrays = new ArrayList<>();
arrays.add(new Integer[]{1, 2});
arrays.add(new Integer[]{3, 4});
Collections.sort(arrays, new Comparator<Integer[]>() {
public int compare(Integer[] a, Integer[] b) {
return 1; // FIX this according to your needs
}
});
compare() above is just a stub, you should implement it according to the documentation and it could be replaced with a lambda expression. In the code above that would be: Collections.sort(arrays, (a, b) -> 1).
You have to write a Comparator and compare method override where you can use your function to calculate comp value
#Override
public int compare(Integer[] o1, Integer[] o2) {
int o1Number=ratingFunction(o1) ;
int o2Number=ratingFunction(o2) ;
int cmp=o1Number.compareTo(o2Number);
return cmp;
}
You can either use comparator to sort list in descending order or you can use Collections sort method and then use reverse method to make it descending order,
something like this :
List<Integer> numberList =new ArrayList<Integer>();
numberList.add(3);
numberList.add(1);
numberList.add(2);
//before sort
for (Integer integer : numberList) {
System.out.println(integer);
}
//sorting
Collections.sort(numberList);
Collections.reverse(numberList);
//after sort
for (Integer integer : numberList) {
System.out.println(integer);
}
You might want to use stream api for that. So let's say we have the scoring function (I simplified it for the sake of example).
public static double evaluate(int[] arr){
return Arrays.stream(arr).sum() / arr.length;
}
Now we can use it with Comparator.comparing method:
List<int[]> list = Arrays.asList(new int[]{4, 5},
new int[]{2, 3}, new int[]{0, 1});
List<int[]> sorted = list.stream().
sorted(Comparator.comparing(Main::evaluate)).
collect(Collectors.toList());
sorted.forEach(x -> System.out.println(Arrays.toString(x)));
The idea behind the code is quite simple, you provide a comparator which defines how to sort int[] arrays. I hope this helps.

How to find the permutation of a sort in Java

I want to sort an array and find the index of each element in the sorted order.
So for instance if I run this on the array:
[3,2,4]
I'd get:
[1,0,2]
Is there an easy way to do this in Java?
Let's assume your elements are stored in an array.
final int[] arr = // elements you want
List<Integer> indices = new ArrayList<Integer>(arr.length);
for (int i = 0; i < arr.length; i++) {
indices.add(i);
}
Comparator<Integer> comparator = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return Integer.compare(arr[i], arr[j]);
}
}
Collections.sort(indices, comparator);
Now indices contains the indices of the array, in their sorted order. You can convert that back to an int[] with a straightforward enough for loop.
import java.util.*;
public class Testing{
public static void main(String[] args){
int[] arr = {3, 2, 4, 6, 5};
TreeMap map = new TreeMap();
for(int i = 0; i < arr.length; i++){
map.put(arr[i], i);
}
System.out.println(Arrays.toString(map.values().toArray()));
}
}
One way to achieve this is to make a list of pairs with the starting index as the second part of the pair. Sort the list of pairs lexicographically, then read off the starting positions from the sorted array.
Starting array:
[3,2,4]
Add pairs with starting indexes:
[(3,0), (2,1), (4,2)]
Sort it lexicographically
[(2,1), (3,0), (4,2)]
then read off the second part of each pair
[1,0,2]
import java.io.*;
public class Sample {
public static void main(String[] args) {
int[] data = {0, 3, 2, 4, 6, 5, 10};//case:range 0 - 10
int i, rangeHigh = 10;
int [] rank = new int[rangeHigh + 1];
//counting sort
for(i=0; i< data.length ;++i) ++rank[data[i]];
for(i=1; i< rank.length;++i) rank[i] += rank[i-1];
for(i=0;i<data.length;++i)
System.out.print((rank[data[i]]-1) + " ");//0 2 1 3 5 4 6
}
}
As an update, this is relatively easy to do in Java 8 using the streams API.
public static int[] sortedPermutation(final int[] items) {
return IntStream.range(0, items.length)
.mapToObj(value -> Integer.valueOf(value))
.sorted((i1, i2) -> Integer.compare(items[i1], items[i2]))
.mapToInt(value -> value.intValue())
.toArray();
}
It somewhat unfortunately requires a boxing and unboxing step for the indices, as there is no .sorted(IntComparator) method on IntStream, or even an IntComparator functional interface for that matter.
To generalize to a List of Comparable objects is pretty straightforward:
public static <K extends Comparable <? super K>> int[] sortedPermutation(final List<K> items) {
return IntStream.range(0, items.size())
.mapToObj(value -> Integer.valueOf(value))
.sorted((i1, i2) -> items.get(i1).compareTo(items.get(i2)))
.mapToInt(value -> value.intValue())
.toArray();
}

Java Array Sort descending?

Is there any EASY way to sort an array in descending order like how they have a sort in ascending order in the Arrays class?
Or do I have to stop being lazy and do this myself :[
You could use this to sort all kind of Objects
sort(T[] a, Comparator<? super T> c)
Arrays.sort(a, Collections.reverseOrder());
Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error
no suitable method found for sort(int[],comparator)
That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.
The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.
for a list
Collections.sort(list, Collections.reverseOrder());
for an array
Arrays.sort(array, Collections.reverseOrder());
You can use this:
Arrays.sort(data, Collections.reverseOrder());
Collections.reverseOrder() returns a Comparator using the inverse natural order. You can get an inverted version of your own comparator using Collections.reverseOrder(myComparator).
an alternative could be (for numbers!!!)
multiply the Array by -1
sort
multiply once again with -1
Literally spoken:
array = -Arrays.sort(-array)
without explicit comparator:
Collections.sort(list, Collections.reverseOrder());
with explicit comparator:
Collections.sort(list, Collections.reverseOrder(new Comparator()));
It's not directly possible to reverse sort an array of primitives (i.e., int[] arr = {1, 2, 3};) using Arrays.sort() and Collections.reverseOrder() because those methods require reference types (Integer) instead of primitive types (int).
However, we can use Java 8 Stream to first box the array to sort in reverse order:
// an array of ints
int[] arr = {1, 2, 3, 4, 5, 6};
// an array of reverse sorted ints
int[] arrDesc = Arrays.stream(arr).boxed()
.sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(arrDesc)); // outputs [6, 5, 4, 3, 2, 1]
First you need to sort your array using:
Collections.sort(myArray);
Then you need to reverse the order from ascending to descending using:
Collections.reverse(myArray);
Java 8:
Arrays.sort(list, comparator.reversed());
Update:
reversed() reverses the specified comparator. Usually, comparators order ascending, so this changes the order to descending.
For array which contains elements of primitives if there is org.apache.commons.lang(3) at disposal easy way to reverse array (after sorting it) is to use:
ArrayUtils.reverse(array);
When an array is a type of Integer class then you can use below:
Integer[] arr = {7, 10, 4, 3, 20, 15};
Arrays.sort(arr, Collections.reverseOrder());
When an array is a type of int data type then you can use below:
int[] arr = {7, 10, 4, 3, 20, 15};
int[] reverseArr = IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();
I don't know what your use case was, however in addition to other answers here another (lazy) option is to still sort in ascending order as you indicate but then iterate in reverse order instead.
For discussions above, here is an easy example to sort the primitive arrays in descending order.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
Arrays.sort(nums);
// reverse the array, just like dumping the array!
// swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
// swap(2nd, 2nd-last) <= 2nd: i++, 2nd-last: j--
// swap(3rd, 3rd-last) <= 3rd: i++, 3rd-last: j--
//
for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
// dump the array (for Java 4/5/6/7/8/9)
for (int i = 0; i < nums.length; i++) {
System.out.println("nums[" + i + "] = " + nums[i]);
}
}
}
Output:
nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0
Another solution is that if you're making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).
For Example :
public int compareTo(freq arg0)
{
int ret=0;
if(this.magnitude>arg0.magnitude)
ret= 1;
else if (this.magnitude==arg0.magnitude)
ret= 0;
else if (this.magnitude<arg0.magnitude)
ret= -1;
return ret;
}
Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it's magnitude. So in order to correct that, you switch the values returned by the < and >. This gives you the following :
public int compareTo(freq arg0)
{
int ret=0;
if(this.magnitude>arg0.magnitude)
ret= -1;
else if (this.magnitude==arg0.magnitude)
ret= 0;
else if (this.magnitude<arg0.magnitude)
ret= 1;
return ret;
}
To make use of this compareTo, we simply call Arrays.sort(mFreq) which will give you the sorted array freq [] mFreq.
The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I'd encourage you not to think that way, it actually isn't. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.
For 2D arrays to sort in descending order you can just flip the positions of the parameters
int[][] array= {
{1, 5},
{13, 1},
{12, 100},
{12, 85}
};
Arrays.sort(array, (a, b) -> Integer.compare(a[1], b[1])); // for ascending order
Arrays.sort(array, (b, a) -> Integer.compare(a[1], b[1])); // for descending order
Output for descending
12, 100
12, 85
1, 5
13, 1
You could use stream operations (Collections.stream()) with Comparator.reverseOrder().
For example, say you have this collection:
List<String> items = new ArrayList<>();
items.add("item01");
items.add("item02");
items.add("item03");
items.add("item04");
items.add("item04");
To print the items in their "natural" order you could use the sorted() method (or leave it out and get the same result):
items.stream()
.sorted()
.forEach(item -> System.out.println(item));
Or to print them in descending (reverse) order, you could use the sorted method that takes a Comparator and reverse the order:
items.stream()
.sorted(Comparator.reverseOrder())
.forEach(item -> System.out.println(item));
Note this requires the collection to have implemented Comparable (as do Integer, String, etc.).
There is a lot of mess going on here - people suggest solutions for non-primitive values, try to implement some sorting algos from the ground, give solutions involving additional libraries, showing off some hacky ones etc. The answer to the original question is 50/50. For those who just want to copy/paste:
// our initial int[] array containing primitives
int[] arrOfPrimitives = new int[]{1,2,3,4,5,6};
// we have to convert it into array of Objects, using java's boxing
Integer[] arrOfObjects = new Integer[arrOfPrimitives.length];
for (int i = 0; i < arrOfPrimitives.length; i++)
arrOfObjects[i] = new Integer(arrOfPrimitives[i]);
// now when we have an array of Objects we can use that nice built-in method
Arrays.sort(arrOfObjects, Collections.reverseOrder());
arrOfObjects is {6,5,4,3,2,1} now. If you have an array of something other than ints - use the corresponding object instead of Integer.
Simple method to sort an int array descending:
private static int[] descendingArray(int[] array) {
Arrays.sort(array);
int[] descArray = new int[array.length];
for(int i=0; i<array.length; i++) {
descArray[i] = array[(array.length-1)-i];
}
return descArray;
}
Adding my answer in here for a couple of different scenarios
For an Array
Arrays.sort(a, Comparator.reverseOrder());
FWIW Lists
Lists.reverse(a);
Any and all Collections
Collections.reverse(a);
I know that this is a quite old thread, but here is an updated version for Integers and Java 8:
Arrays.sort(array, (o1, o2) -> o2 - o1);
Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).
This also works for any other kinds of Objects. Say:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());
This worked for me:
package doublearraysort;
import java.util.Arrays;
import java.util.Collections;
public class Gpa {
public static void main(String[] args) {
// initializing unsorted double array
Double[] dArr = new Double[] {
new Double(3.2),
new Double(1.2),
new Double(4.7),
new Double(3.3),
new Double(4.6),
};
// print all the elements available in list
for (double number : dArr) {
System.out.println("GPA = " + number);
}
// sorting the array
Arrays.sort(dArr, Collections.reverseOrder());
// print all the elements available in list again
System.out.println("The sorted GPA Scores are:");
for (double number : dArr) {
System.out.println("GPA = " + number);
}
}
}
Output:
GPA = 3.2
GPA = 1.2
GPA = 4.7
GPA = 3.3
GPA = 4.6
The sorted GPA Scores are:
GPA = 4.7
GPA = 4.6
GPA = 3.3
GPA = 3.2
GPA = 1.2
public double[] sortArrayAlgorithm(double[] array) { //sort in descending order
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] >= array[j]) {
double x = array[i];
array[i] = array[j];
array[j] = x;
}
}
}
return array;
}
just use this method to sort an array of type double in descending order, you can use it to sort arrays of any other types(like int, float, and etc) just by changing the "return type", the "argument type" and the variable "x" type to the corresponding type. you can also change ">=" to "<=" in the if condition to make the order ascending.
Another way with Comparator
import java.util.Arrays;
import java.util.Comparator;
...
Integer[] aInt = {6,2,3,4,1,5,7,8,9,10};
Arrays.sort(aInt, Comparator.reverseOrder() );
It's good sometimes we practice over an example, here is a full one:
sortdesc.java
import java.util.Arrays;
import java.util.Collections;
class sortdesc{
public static void main(String[] args){
// int Array
Integer[] intArray=new Integer[]{
new Integer(15),
new Integer(9),
new Integer(16),
new Integer(2),
new Integer(30)};
// Sorting int Array in descending order
Arrays.sort(intArray,Collections.reverseOrder());
// Displaying elements of int Array
System.out.println("Int Array Elements in reverse order:");
for(int i=0;i<intArray.length;i++)
System.out.println(intArray[i]);
// String Array
String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};
// Sorting String Array in descending order
Arrays.sort(stringArray,Collections.reverseOrder());
// Displaying elements of String Array
System.out.println("String Array Elements in reverse order:");
for(int i=0;i<stringArray.length;i++)
System.out.println(stringArray[i]);}}
compiling it...
javac sortdec.java
calling it...
java sortdesc
OUTPUT
Int Array Elements in reverse order:
30
16
15
9
2
String Array Elements in reverse order:
PP
OO
FF
DD
AA
If you want to try an alphanumeric array...
//replace this line:
String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};
//with this:
String[] stringArray=new String[]{"10FF","20AA","50AA"};
you gonna get the OUTPUT as follow:
50AA
20AA
10FF
source
There is a way that might be a little bit longer, but it works fine. This is a method to sort an int array descendingly.
Hope that this will help someone ,,, some day:
public static int[] sortArray (int[] array) {
int [] sortedArray = new int[array.length];
for (int i = 0; i < sortedArray.length; i++) {
sortedArray[i] = array[i];
}
boolean flag = true;
int temp;
while (flag) {
flag = false;
for (int i = 0; i < sortedArray.length - 1; i++) {
if(sortedArray[i] < sortedArray[i+1]) {
temp = sortedArray[i];
sortedArray[i] = sortedArray[i+1];
sortedArray[i+1] = temp;
flag = true;
}
}
}
return sortedArray;
}
I had the below working solution
public static int[] sortArrayDesc(int[] intArray){
Arrays.sort(intArray); //sort intArray in Asc order
int[] sortedArray = new int[intArray.length]; //this array will hold the sorted values
int indexSortedArray = 0;
for(int i=intArray.length-1 ; i >= 0 ; i--){ //insert to sortedArray in reverse order
sortedArray[indexSortedArray ++] = intArray [i];
}
return sortedArray;
}
Here is how I sorted a primitive type int array.
int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));
Result:
[1, 4, 7, 9]
I know many answers are here, but still thinks , none of them tried using core java.
And using collection api , you will end up wasting so much memory and reseduals.
here is a try with pure core concepts , and yes this may be better way if you are more concerned about memory footprints.
int[] elements = new int [] {10,999,999,-58,548,145,255,889,1,1,4,5555,0,-1,-52};
//int[] elements = null;
if(elements != null && elements.length >1)
{
int max = 0, index = 0;
for(int i =0;i<elements.length;i++)//find out what is Max
{
if(elements[i] > max)
{
max = elements[i];
index = i;
}
}
elements[index] = elements[0];//Swap the places
elements[0] = max;
for(int i =0;i < elements.length;i++)//loop over element
{
for(int j = i+1;j < elements.length;j++)//loop to compare the elements
{
if(elements[j] > elements[i])
{
max = elements[j];
elements[j] = elements[i];
elements[i] = max;
}
}
}
}//i ended up using three loops and 2 extra variables
System.out.println(Arrays.toString(elements));//if null it will print null
// still love to learn more, please advise if we can do it better.
Love to learn from you too !

How to convert an ArrayList containing Integers to primitive int array?

I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?
List<Integer> x = new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
If you are using java-8 there's also another way to do this.
int[] arr = list.stream().mapToInt(i -> i).toArray();
What it does is:
getting a Stream<Integer> from the list
obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5)
getting the array of int by calling toArray
You could also explicitly call intValue via a method reference, i.e:
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
It's also worth mentioning that you could get a NullPointerException if you have any null reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:
//.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();
Example:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]
list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]
You can convert, but I don't think there's anything built in to do it automatically:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
(Note that this will throw a NullPointerException if either integers or any element within it is null.)
EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
Google Guava
Google Guava provides a neat way to do this by calling Ints.toArray.
List<Integer> list = ...;
int[] values = Ints.toArray(list);
Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this.
import org.apache.commons.lang.ArrayUtils;
...
List<Integer> list = new ArrayList<Integer>();
list.add(new Integer(1));
list.add(new Integer(2));
int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));
However, as Jon showed, it is pretty easy to do this by yourself instead of using external libraries.
I believe iterating using the List's iterator is a better idea, as list.get(i) can have poor performance depending on the List implementation:
private int[] buildIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
}
Java 8:
int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();
Arrays.setAll()
List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
int[] n = new int[x.size()];
Arrays.setAll(n, x::get);
System.out.println("Array of primitive ints: " + Arrays.toString(n));
Output:
Array of primitive ints: [7, 9, 13]
The same works for an array of long or double, but not for arrays of boolean, char, byte, short or float. If you’ve got a really huge list, there’s even a parallelSetAll method that you may use instead.
To me this is good and elgant enough that I wouldn’t want to get an external library nor use streams for it.
Documentation link: Arrays.setAll(int[], IntUnaryOperator)
using Dollar should be quite simple:
List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4
int[] array = $($(list).toArray()).toIntArray();
I'm planning to improve the DSL in order to remove the intermediate toArray() call
This works nice for me :)
Found at https://www.techiedelight.com/convert-list-integer-array-int/
import java.util.Arrays;
import java.util.List;
class ListUtil
{
// Program to convert list of integer to array of int in Java
public static void main(String args[])
{
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] primitive = list.stream()
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(primitive));
}
}
Arrays.setAll() will work for most scenarios:
Integer List to primitive int array:
public static int[] convert(final List<Integer> list)
{
final int[] out = new int[list.size()];
Arrays.setAll(out, list::get);
return out;
}
Integer List (made of Strings) to primitive int array:
public static int[] convert(final List<String> list)
{
final int[] out = new int[list.size()];
Arrays.setAll(out, i -> Integer.parseInt(list.get(i)));
return out;
}
Integer array to primitive int array:
public static int[] convert(final Integer[] array)
{
final int[] out = new int[array.length];
Arrays.setAll(out, i -> array[i]);
return out;
}
Primitive int array to Integer array:
public static Integer[] convert(final int[] array)
{
final Integer[] out = new Integer[array.length];
Arrays.setAll(out, i -> array[i]);
return out;
}
It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.
Just go with Apache Commons
Java 8
int[] array = list.stream().mapToInt(i->i).toArray();
OR
int[] array = list.stream().mapToInt(Integer::intValue).toArray();
If you're using Eclipse Collections, you can use the collectInt() method to switch from an object container to a primitive int container.
List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
MutableIntList intList =
ListAdapter.adapt(integers).collectInt(i -> i);
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());
If you can convert your ArrayList to a FastList, you can get rid of the adapter.
Assert.assertArrayEquals(
new int[]{1, 2, 3, 4, 5},
Lists.mutable.with(1, 2, 3, 4, 5)
.collectInt(i -> i).toArray());
Note: I am a committer for Eclipse collections.
You can simply copy it to an array:
int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
Not too fancy; but, hey, it works...
Next lines you can find convertion from int[] -> List -> int[]
private static int[] convert(int[] arr) {
List<Integer> myList=new ArrayList<Integer>();
for(int number:arr){
myList.add(number);
}
}
int[] myArray=new int[myList.size()];
for(int i=0;i<myList.size();i++){
myArray[i]=myList.get(i);
}
return myArray;
}
This code segment is working for me, try this:
Integer[] arr = x.toArray(new Integer[x.size()]);
Worth to mention ArrayList should be declared like this:
ArrayList<Integer> list = new ArrayList<>();
A very simple one-line solution is:
Integer[] i = arrlist.stream().toArray(Integer[]::new);
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
int[] result = null;
StringBuffer strBuffer = new StringBuffer();
for (Object o : list) {
strBuffer.append(o);
result = new int[] { Integer.parseInt(strBuffer.toString()) };
for (Integer i : result) {
System.out.println(i);
}
strBuffer.delete(0, strBuffer.length());
}
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);
access arr like normal int[].

Categories