Conversion of int array to ArrayList - java

I have a function that gets an array of primitive data (int), I need to return the array of two elements the smallest and the largest number. If length of the array is 1 then just return two first elements int the array. I came up with such solution:
public static int[] minMax(int[] arr) {
if (arr.length==1)
return new int[]{arr[0],arr[0]} ;// return if arr is 1 element
else {
ArrayList<Integer> ar = new ArrayList<Integer>();
//?
return new int[]{Collections.max(ar),Collections.min(ar)};
}
}
But how do I convert an array to an ArrayList? Is there a more efficient way maybe?

By calling Collections.min and Collections.max, you're iterating over the array twice. You can cut this time down by streaming the array and letting it do the heavy lifting, as James Mudd suggested. However, note that by doing so you'd be wasting time on calculating the sum and accumulating the count of the elements, which you don't care about. It may be more efficient to calculated these yourself:
public static int[] minMax(int[] arr) {
// Assuming arr has at least one element
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; ++i) {
int curr = arr[i];
if (curr < min) {
min = curr;
} else if (curr > max) {
max = curr;
}
}
return new int[]{min, max};
}

You could use IntSummaryStatistics the method would look like
public static int[] minMax(int[] arr) {
IntSummaryStatistics intSummaryStatistics = Arrays.stream(arr).summaryStatistics();
return new int[] {intSummaryStatistics.getMin(), intSummaryStatistics.getMax()};
}

Here's another way of solving this task with streams.
Instead, using IntSummuryStatistics we can provide an array of two elements as a container of the resulting values while applying collect and manually define to accumulate stream elements in it.
public static int[] minMax(int[] sourceArr) {
if (sourceArr.length == 0) throw new IllegalArgumentException(); // source array is empty
return Arrays.stream(sourceArr)
.collect(
() -> new int[]{sourceArr[0], sourceArr[0]}, // mutable container
(arr, next) -> { // accumulator - populating the container with elements of the stream
arr[0] = Math.min(arr[0], next);
arr[1] = Math.max(arr[1], next);
},
(left, right) -> { // combiner - merging containers in parallel
left[0] = Math.min(left[0], right[0]);
left[1] = Math.max(left[1], right[1]);
});
}
main()
public static int[] minMax(int[] sourceArr) {
System.out.println(Arrays.toString(minMax(new int[]{3, 5, -3, 8, 9})));
System.out.println(Arrays.toString(minMax(new int[]{3, -1, 3, 12, 27})));
}
Output:
[-3, 9]
[-1, 27]
But how do I convert an array to an ArrayList?
It's not possible to convert an array of primitives into a List directly. When you have an array of reference type (like Integer, BigDecimal, etc.) you can use Arrays.asList() to fixed-size list wrapped around the given array. But it wouldn't work with primitive arrays.
In order to translate int[] into a List<Integer> you have to create a new list and populate it with the contents of the array.
So your actual goal is to obtain the result as a list, the code provided above might be changed like that:
public static List<Integer> minMax(int[] sourceArr) {
if (sourceArr.length == 0) throw new IllegalArgumentException(); // source array is empty
return Arrays.stream(sourceArr)
.collect(
() -> Arrays.asList(sourceArr[0], sourceArr[0]), // mutable container
(list, next) -> { // accumulator - populating the container with elements of the stream
list.set(0, Math.min(list.get(0), next));
list.set(1, Math.max(list.get(1), next));
},
(left, right) -> { // combiner - merging containers in parallel
left.set(0, Math.min(left.get(0), right.get(0)));
left.set(1, Math.max(left.get(1), right.get(1)));
});
}

Related

Find indexes of highest values in array. Can be 1-* values

I know how to find the highest value and index in a array(list). But I dont know how to get the indexes if there are multiple highest values in a array. I want to create a method/function that can two things: fill the array(list) with only one index if there is only one highest value, or create a arraylist if there are multiple highest values. For example I give two array's:
Array1={42,3,42,42,42,5,8};
I want to get the all the indexes of value 42 in a new array(list).
Array2={42,3,35,67};
I want to create a array(list) with only one index of value 42.
Try this for multiple indexes
List<Integer> list = new ArrayList<>();
int array[] = {1,1,2,4,5,3,1,5};
int max = array[0];
list.add(0);
for(int i=1;i<array.length;i++){
if(max<array[i]){
max = array[i];
list.clear();
list.add(i);
}else if(max==array[i])
list.add(i);
}
System.out.println(list);
For single index, use an extra variable, to store it it.
Using Java 8 features and assuming the array is not empty:
int maxValue = Arrays.stream(array)
.max()
.getAsInt();
int[] maxIndexes = IntStream.range(0, array.length)
.filter(i -> array[i] == maxValue)
.toArray();
That's 2 iterations where first you find the max value and then the indexes where an array element is equal to the max value.
Some documentation if you are not familiar with some classes/methods above:
IntStream, toArray(), getAsInt()
Depending on your scenario, having a small data set or a large data set, you might want to process the items sequentially or in parallel.
NOTE: the following code contains JUnit #Test annotation and AssertJ assertions.
Solution: sequential, one pass, small data set
This solution parses the array and keeps track of maximum and current maximum indexes. If a new maximum is found the indexes are cleared and the new maximum indexes are inserted.
#Test
public void sequential_algorithm_return_max_with_indexes() {
int[] values = new int[]{42, 3, 42, 42, 42, 5, 8};
int maxValue = Integer.MIN_VALUE;
List<Integer> maxValueIndexes = new ArrayList<>();
for (int index = 0; index < values.length; index++) {
int value = values[index];
if (value == maxValue) {
maxValueIndexes.add(index);
} else {
if (value > maxValue) {
maxValue = value;
maxValueIndexes.clear();
maxValueIndexes.add(index);
}
}
}
assertThat(maxValue).isEqualTo(42);
assertThat(maxValueIndexes).containsExactly(0, 2, 3, 4);
}
Solution: parallel, large data set
Streams are flexible and allow parallel processing.
Bellow data is represented as a pair of index-value instead of an array. This is done in order to transform the array of pairs into a stream and keep track of indexes.
Because this supposed to work in parallel, reduce method accepts 3 arguments - initial value, accumulator and combiner. This means that multiple buckets run in parallel. For each bucket there is an initial value and an accumulator used to process items sequentially. Then the parallel results of buckets are combined using the combiner argument.
#Test
public void parallel_algorithm_return_max_with_indexes() {
Pair<Integer, Integer>[] values = new Pair[]{
new Pair<>(0, 42),
new Pair<>(1, 3),
new Pair<>(2, 42),
new Pair<>(3, 42),
new Pair<>(4, 42),
new Pair<>(5, 5),
new Pair<>(6, 8),
};
ValueIndexes<Integer> maxValueIndexes = Arrays.stream(values)
.parallel()
.reduce(
new ValueIndexes<>(Integer.MIN_VALUE),
(ValueIndexes<Integer> valueIndexes, Pair<Integer, Integer> value) -> {
if (valueIndexes.getValue() == value.getValue()) {
valueIndexes.addIndex(value.getKey());
} else {
if (value.getValue() > valueIndexes.getValue()) {
valueIndexes = new ValueIndexes<>(value.getValue());
valueIndexes.addIndex(value.getKey());
}
}
return valueIndexes;
},
(valueIndexes1, valueIndexes2) -> {
if (valueIndexes1.getValue() == valueIndexes2.getValue()) {
ValueIndexes<Integer> valueIndexes = new ValueIndexes<>(valueIndexes1.getValue());
valueIndexes.addIndexes(valueIndexes1.getIndexes());
valueIndexes.addIndexes(valueIndexes2.getIndexes());
return valueIndexes;
} else {
if (valueIndexes1.getValue() > valueIndexes2.getValue()) {
return valueIndexes1;
} else {
return valueIndexes2;
}
}
}
);
assertThat(maxValueIndexes.getValue()).isEqualTo(42);
assertThat(maxValueIndexes.getIndexes()).containsExactlyInAnyOrder(0, 2, 3, 4);
}
private class ValueIndexes<T> {
private T value;
private List<Integer> indexes = new ArrayList<>();
public ValueIndexes(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public Iterable<Integer> getIndexes() {
return indexes;
}
public void addIndexes(Iterable<Integer> indexes) {
indexes.forEach(this::addIndex);
}
public void addIndex(int index) {
indexes.add(index);
}
}

An efficient way to convert List<Integer> to int[] ( array ) without iteration

public static int[] convertListToArray(List<Integer> listResult) {
int[] result = new int[listResult.size()];
int i= 0;
for (int num : listResult) {
result[i++] = num;
}
return result;
}
Is there an efficient way to convert List to array without iterating List explicitly ?
Maybe it is possible by using methods like:
Arrays.copyOf(int [] origin , int newLength );
System.arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
I know that there is a solution described here. However, I particularly interested in an efficient way of converting List<Integer> to int[]
Given the need to convert from Integer to int, I don't think you're going to find something more efficient than what you have, if I assume you're talking about runtime efficiency.
You might find converting to Integer[] first and then looping might be more efficient (below), but you might not, too. You'd have to test it in your specific scenario and see.
Here's that example:
int size = listResult.size();
int[] result = new int[size];
Integer[] temp = listResult.toArray(new Integer[size]);
for (int n = 0; n < size; ++n) {
result[n] = temp[n];
}
If efficiency is your primary concern, I think you can use your solution and make it more efficient by using an indexed for loop on the listResult if it is RandomAccess. However this makes the code much less readable, and you'd have to benchmark it for your use cases to see if it is more efficient.
public static int[] convertListToArray(List<Integer> listResult) {
int size = listResult.size();
int[] result = new int[size];
if (listResult instanceof RandomAccess)
{
for (int i = 0; i < size; i++)
{
result[i] = listResult.get(i);
}
}
else
{
int i = 0;
for (int num : listResult) {
result[i++] = num;
}
}
return result;
}
If you use Java 8 and would like to write less code you can use the Streams library.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] array = list.stream().mapToInt(i -> i).toArray();
If you are open to using a third party library, you can Eclipse Collections as follows.
MutableList<Integer> list = Lists.mutable.with(1, 2, 3, 4, 5);
int[] array = list.collectInt(i -> i).toArray();
The following is slightly more code, but is the most efficient solution I could come up with using Eclipse Collections.
MutableList<Integer> list = Lists.mutable.with(1, 2, 3, 4, 5);
int[] array = new int[list.size()];
list.forEachWithIndex((each, index) -> array[index] = each);
If you need to use the java.util.List interface, the ListIterate utility class can be used from Eclipse Collections.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] array = new int[list.size()];
ListIterate.forEachWithIndex(list, (each, index) -> array[index] = each);
The ListIterate utility will use different iteration code for RandomAccess lists and non-RandomAccess lists.
The most efficient thing to do would be to change the List<Integer> to a MutableIntList in Eclipse Collections or another library that has support for primitive collections.
Note: I am a committer for Eclipse Collections.
In Java 8:
int[] anArray = list.stream()
.filter(Objects::nonNull)
.mapToInt(Integer::intValue)
.toArray();
There is efficient way you could do this Java. However, this could open room for someone to create the generic function (depend on demand).
Just like this sample i wrote, I suggest you do the same to the specific knowledge of your program.
// Generic function to convert set to list
public static <T> ArrayList<T> convertSetToList(Set<T> set)
{
// create an empty list
ArrayList<T> list = new ArrayList<>();
// push each element in the set into the list
for (T t : set)
list.add(t);
// return the list
return list;
}

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 can I convert int[] to Integer[] in Java?

I have a large dataset of length 4 int[] and I want to count the number of times that each particular combination of 4 integers occurs. This is very similar to counting word frequencies in a document.
I want to create a Map<int[], double> that maps each int[] to a running count as the list is iterated over, but Map doesn't take primitive types.
So I made Map<Integer[], Double>.
My data is stored as an ArrayList<int[]>, so my loop should be something like:
ArrayList<int[]> data = ... // load a dataset`
Map<Integer[], Double> frequencies = new HashMap<Integer[], Double>();
for(int[] q : data) {
// **DO SOMETHING TO convert q from int[] to Integer[] so I can put it in the map
if(frequencies.containsKey(q)) {
frequencies.put(q, tfs.get(q) + p);
} else {
frequencies.put(q, p);
}
}
I'm not sure what code I need at the comment to make this work to convert an int[] to an Integer[]. Or maybe I'm fundamentally confused about the right way to do this.
Native Java 8 (one line)
With Java 8, int[] can be converted to Integer[] easily:
int[] data = {1,2,3,4,5,6,7,8,9,10};
// To boxed array
Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );
// To boxed list
List<Integer> you = Arrays.stream( data ).boxed().collect( Collectors.toList() );
List<Integer> like = IntStream.of( data ).boxed().collect( Collectors.toList() );
As others stated, Integer[] is usually not a good map key.
But as far as conversion goes, we now have a relatively clean and native code.
If you want to convert an int[] to an Integer[], there isn't an automated way to do it in the JDK. However, you can do something like this:
int[] oldArray;
... // Here you would assign and fill oldArray
Integer[] newArray = new Integer[oldArray.length];
int i = 0;
for (int value : oldArray) {
newArray[i++] = Integer.valueOf(value);
}
If you have access to the Apache lang library, then you can use the ArrayUtils.toObject(int[]) method like this:
Integer[] newArray = ArrayUtils.toObject(oldArray);
Convert int[] to Integer[]:
import java.util.Arrays;
...
int[] aint = {1,2,3,4,5,6,7,8,9,10};
Integer[] aInt = new Integer[aint.length];
Arrays.setAll(aInt, i -> aint[i]);
Using regular for-loop without external libraries:
Convert int[] to Integer[]:
int[] primitiveArray = {1, 2, 3, 4, 5};
Integer[] objectArray = new Integer[primitiveArray.length];
for(int ctr = 0; ctr < primitiveArray.length; ctr++) {
objectArray[ctr] = Integer.valueOf(primitiveArray[ctr]); // returns Integer value
}
Convert Integer[] to int[]:
Integer[] objectArray = {1, 2, 3, 4, 5};
int[] primitiveArray = new int[objectArray.length];
for(int ctr = 0; ctr < objectArray.length; ctr++) {
primitiveArray[ctr] = objectArray[ctr].intValue(); // returns int value
}
Presumably you want the key to the map to match on the value of the elements instead of the identity of the array. In that case you want some kind of object that defines equals and hashCode as you would expect. Easiest is to convert to a List<Integer>, either an ArrayList or better use Arrays.asList. Better than that you can introduce a class that represents the data (similar to java.awt.Rectangle but I recommend making the variables private final, and the class final too).
The proper solution is to use this class as a key in the map wrapping the actual int[].
public class IntArrayWrapper {
int[] data;
public IntArrayWrapper(int[] data) {
this.data = data;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
IntArrayWrapper that = (IntArrayWrapper) o;
if (!Arrays.equals(data, that.data))
return false;
return true;
}
#Override
public int hashCode() {
return data != null ? Arrays.hashCode(data) : 0;
}
}
And change your code like this:
Map<IntArrayWrapper, Double > freqs = new HashMap<IntArrayWrapper, Double>();
for (int[] data : datas) {
IntArrayWrapper wrapper = new IntArrayWrapper(data);
if (freqs.containsKey(wrapper)) {
freqs.put(wrapper, freqs.get(wrapper) + p);
}
freqs.put(wrapper, p);
}
Convert int[] to Integer[]
public static Integer[] toConvertInteger(int[] ids) {
Integer[] newArray = new Integer[ids.length];
for (int i = 0; i < ids.length; i++) {
newArray[i] = Integer.valueOf(ids[i]);
}
return newArray;
}
Convert Integer[] to int[]
public static int[] toint(Integer[] WrapperArray) {
int[] newArray = new int[WrapperArray.length];
for (int i = 0; i < WrapperArray.length; i++) {
newArray[i] = WrapperArray[i].intValue();
}
return newArray;
}
Rather than write your own code, you can use an IntBuffer to wrap the existing int[] without having to copy the data into an Integer array:
int[] a = {1, 2, 3, 4};
IntBuffer b = IntBuffer.wrap(a);
IntBuffer implements comparable, so you are able to use the code you already have written. Formally, maps compare keys such that a.equals(b) is used to say two keys are equal, so two IntBuffers with array 1,2,3 - even if the arrays are in different memory locations - are said to be equal and so will work for your frequency code.
ArrayList<int[]> data = ... // Load a dataset`
Map<IntBuffer, Double> frequencies = new HashMap<IntBuffer, Double>();
for(int[] a : data) {
IntBuffer q = IntBuffer.wrap(a);
if(frequencies.containsKey(q)) {
frequencies.put(q, tfs.get(q) + p);
} else {
frequencies.put(q, p);
}
}
This worked like a charm!
int[] mInt = new int[10];
Integer[] mInteger = new Integer[mInt.length];
List<Integer> wrapper = new AbstractList<Integer>() {
#Override
public int size() {
return mInt.length;
}
#Override
public Integer get(int i) {
return mInt[i];
}
};
wrapper.toArray(mInteger);
Though the below compiles, it throws a ArrayStoreException at runtime.
Converting an int[], to an Integer[]:
int[] old;
...
Integer[] arr = new Integer[old.length];
System.arraycopy(old, 0, arr, 0, old.length);
I must admit I was a bit surprised that this compiles, given System.arraycopy being lowlevel and everything, but it does. At least in Java 7.
You can convert the other way just as easily.
I am not sure why you need a Double in your map. In terms of what you're trying to do, you have an int[] and you just want counts of how many times each sequence occurs(?). Why would this require a Double anyway?
I would create a wrapper for the int array with a proper .equals and .hashCode methods to account for the fact that int[] object itself doesn't consider the data in its version of these methods.
public class IntArrayWrapper {
private int values[];
public IntArrayWrapper(int[] values) {
super();
this.values = values;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(values);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IntArrayWrapper other = (IntArrayWrapper) obj;
if (!Arrays.equals(values, other.values))
return false;
return true;
}
}
And then use Google Guava's multiset, which is meant exactly for the purpose of counting occurrences, as long as the element type you put in it has proper .equals and .hashCode methods.
List<int[]> list = ...;
HashMultiset<IntArrayWrapper> multiset = HashMultiset.create();
for (int values[] : list) {
multiset.add(new IntArrayWrapper(values));
}
Then, to get the count for any particular combination:
int cnt = multiset.count(new IntArrayWrapper(new int[] { 0, 1, 2, 3 }));
Int is a primitive. Primitives can’t accept null and have default value. Hence, to accept Null you need to use wrapper class Integer.
Option 1:
int[] nos = { 1, 2, 3, 4, 5 };
Integer[] nosWrapped = Arrays.stream(nos)
.boxed()
.toArray(Integer[]::new);
nosWrapped[5] = null // can store null
Option 2:
You can use any data structure that use wrapper class Integer
int[] nos = { 1, 2, 3, 4, 5 };
List<Integer> = Arrays.asList(nos)
You don't need it. int[] is an object and can be used as a key inside a map.
Map<int[], Double> frequencies = new HashMap<int[], Double>();
is the proper definition of the frequencies map.
This was wrong :-). The proper solution is posted too :-).

Categories