Fastest way to convert ArrayList<Integer> into int[] [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert List<Integer> to int[] in Java?
In Java, is below the fastest solution:
public convert(ArrayList<Integer> IntegerList) {
int s = IntegerList.size();
int[] intArray = new int[s];
for (int i = 0; i < s; i++) {
intArray[i] = IntegerList.get(i).intValue();
}
}
?

The fastest way is to not use an ArrayList<Integer> in the first place. Try TIntArrayList which wraps an int[], or use a int[] from the start.
If you have to use an ArrayList for some reason and you can't fix it, you are need a way which works and performance is less important.
int[] ints = new int[list.size()];
for(int i=0, len = list.size(); i < len; i++)
ints[i] = list.get(i);

I cant think of any better solution than you have now with plain java.
However if you use Guava, You can probably simplify it.
public convert(List<Integer> list) {
int[] ar = Ints.toArray(list); //Ints is the class from Guava library
}

public void convert(ArrayList<Integer> IntegerList) {
int[] intArray = new int[IntegerList.size()];
int count = 0;
for(int i : IntegerList){
intArray[count++] = i;
}
}
UPDATE : Q. but is a foreach loop any faster/better/different from a regular for loop?
A. here

Integer[] intArray = IntegerList.toArray(new Integer[IntegerList.size()]);

Related

unable to pass test case for "remove x element after y number of occurrence in array"

I am trying to get pass a coding challenge. The goal is to remove duplicate (after a defined 'n-th' time) from the array.
For example,
int[] arr;
arr = new int[] {1, 2, 2, 3, 3, 3, 4, 5, 5};
arr = tester(arr,1);//return 1,4. anything having more then 1 occurrence is removed from the //array
I have 2 questions here.
I understand that although java is mainly call by value,
more detail: https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java#:~:text=Longer%20answer%3A,object%20that%20the%20caller%20sees.
and
Is Java "pass-by-reference" or "pass-by-value"?
.
so am I not able to modify/return the value of arr without re-assigning it as I need to use the "new" keyword later on.
example:
I am not able to do the following:
tester(arr,1) //return the original value, as the method has a "new" when converting the
//arraylist into array. There seems to be no work around for this as well..
I am also only passing 2 out of 10 test case in the coding challenge, I am not very sure why. I have also attempted to error handle with string inputs, or length=0 or null, to no success. (or implemented it in hashmap for sake of time complexity)
It does not seem like my logic has an issue, I am just not sure what are the test case as it is hidden.
I believe part of the challenge requires me to return it in the original array, meaning changing the value of arr itself, but i cant find a way to do it without using the new keyword.
Any ideas anyone?
public static int[] tester(int[] data, int n)
{
ArrayList<Integer> storeNon_dup = new ArrayList<Integer>();
//nested for loop to run through the array
//store in arrayList if criteria valid
for(int i = 0; i < data.length; i++)
{
int counter = 0;
for(int j = 0; j< data.length; j++)
{
if(data[i] == data[j])
{
counter++;
}
}
//if not duplicate in n-th occurence, add to list
if(counter<=n)
{
storeNon_dup.add(data[i]);
}
}
//convert arraylist to array
int[] container = new int[storeNon_dup.size()];
for(int i = 0; i<storeNon_dup.size(); i++)
{
container[i] = storeNon_dup.get(i);
}
return container;
}
Alternate solution by using HashMap.
public static List tester(int[] data, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<data.length; i++) {
if(map.containsKey(data[i])) {
map.put(data[i], map.get(data[i])+1);
}else {
map.put(data[i], 1);
}
}
List lst = new ArrayList<Integer>();
for(Integer key : map.keySet()) {
if(map.get(key)<=n) {
lst.add(key);
}
}
return lst;
}

Converting ArrayList<Integer> into int[] won't work in Java

I have been developing a program where I have to convert an ArrayList into an int[]. I do not get any syntax errors when I run the code. However, when I print the int[] to see if it does work, it prints out a random string which is "[I#2a139a55" How can I fix this?
I cannot use an int[] from the start. This program HAS to convert an ArrayList into int[].
ArrayList<Integer> student_id = new ArrayList<Integer>();
student_id.add(6666);
student_id.add(7888);
int[] student_id_array = new int[student_id.size()];
for (int i=0, len = student_id.size(); i < len; i ++){
student_id_array[i] = student_id.get(i);
}
System.out.println(student_id_array);
You are printing out the reference to the array. Use Arrays.toString(int[]).
You can do the converting your ArrayList<Integer> to int[] with one line in Java 8:
int[] student_id_array = student_id.stream().mapToInt(id -> id).toArray();
And if you want to output array's values instead of representation of your array (like [I#2a139a55) use Arrays.toString() method:
System.out.println(Arrays.toString(student_id_array));
That because you are printing the memory address of that array.
try this :
ArrayList<Integer> student_id = new ArrayList<Integer>();
student_id.add(6666);
student_id.add(7888);
int[] student_id_array = new int[student_id.size()];
for (int i=0, len = student_id.size(); i < len; i ++){
student_id_array[i] = student_id.get(i);
}
System.out.println(student_id_array[0]+" "+student_id_array[1]);
Output :
6666 7888
OR use for-loop if you populate the ArrayList later on.

How should I concatenate arrays [duplicate]

This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 7 years ago.
I am using a function that returns some integers
int[] return;
This function is inside a loop like this
public static int[] toEOBArray(double[] tempVal)
{
int[] out;
for (int i = 0; i < 10; i++)
{
out = fixArray(tempVal[i]);
}
return out;
}
What I want is as new arrays come from fixArray to add them to the previous results, so in the end I have a big array that will contain all the small arrays resulting from fixArray
What is the most efficient way of doing this?
My main problem is not knowing how to initialize the array that is to hold all the values.
If you want to work only with arrays, you must first find the length of the concatenated array. Then you can use System.arraycopy to copy the small arrays to the output array.
public static int[] toEOBArray(double[] in)
{
int[][] arrays = new int[10][];
int len = 0;
for (int i = 0; i < 10; i++)
{
arrays[i] = fixArray(tempVal[i]);
len += arrays[i].length;
}
int[] out = new int[len];
int offset = 0;
for (int i = 0; i < 10; i++)
{
System.arraycopy(arrays[i],0,out,offset,arrays[i].length);
offset += arrays[i].length;
}
return out;
}
If you insist on working with native arrays (as opposed to a Collection like ArrayList) then you will want to use ArrayUtils class from Apache Common Lang that adds many Collection-like features to Java native arrays, one of which is addAll:
ArrayUtils.addAll(fixArray, tempVal);

Remove all occurrences of an integer from an int array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I remove all occurrences of an integer, say, 17 in this example from a given array in java?
I tried setting entries to (Integer) null though it doesn't work.
Input array: [0,6,0,17,1,9,17,8,4]
Output array: [0,6,0,1,9,8,4]
for(int i =0;i<ansa.length;i++){
if(ansa[i]==17)
{
ansa[i]=(Integer)null;
}
}
This results in
Exception in thread "main" java.lang.NullPointerException
int[] array = { 0,6,0,17,1,9,17,8,4 };
int[] filtered = Arrays.stream(array).filter(i -> i != 17).toArray();
System.out.println(Arrays.toString(filtered));
:-)
Try this one.
Integer[] array ={0,6,0,17,1,9,17,8,4};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(array ));
list.removeAll(Arrays.asList(17 ));
array =list.toArray(new Integer[0]);
System.out.println(Arrays.toString(array));
I tried setting entries to (Integer) null though it doesn't work.
Of course it doesn't, because the size of the array isn't changed. In order to do this, some of the defined java collections (in particular, the ArrayList and Iterator classes) can provide you of a better approach.
In pseudocode:
Turn array into a List
Iterate over its elements
If the element is the given number
Remove it
Return the List as an Array
You can fill in the blanks, just remember that you can't actually remove an element from an array, because its size is static.
Note: I'm going for the educational approach.
This seems to work - although I suspect people will post better/more efficient solutions.
public void test() {
int[] before = new int[] {0,6,0,17,1,9,17,8,4};
int[] after = remove(before, 17);
System.out.println("Before: "+Arrays.toString(before));
System.out.println("Aftre: "+Arrays.toString(after));
}
private int[] remove(int[] before, int remove) {
// Work out how long it must be.
int keep = 0;
for ( int i = 0; i < before.length; i++ ) {
if(before[i] != remove) {
keep += 1;
}
}
// Make the new one
int[] after = new int[keep];
// Fill it in.
for ( int i = 0, j = 0; i < before.length; i++ ) {
if(before[i] != remove) {
after[j++] = before[i];
}
}
return after;
}
Thats one possible solution:
int[] array1 = new int[]{0,6,0,17,1,9,17,8,4};
ArrayList<Integer> result = new ArrayList<Integer>();
boolean flag = true;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array1.length; j++) {
if(array1[i]==array1[j]&&i!=j) {
flag = false;
}
}
if(flag) {
result.add(array1[i]);
}
else{
flag = true;
}
}
System.out.println(result);
I think, if you don't want to use an ArrayList, you will have to count how many 17 are in the array and create a new one with ansa.length-count fields
You cannot remove items from an array you are currently using a for loop to cycle through. At the moment you are getting to the end of your array and looking for the next value even though you deleted it. The array length indicator (ansa.length) does not auto update as you are thinking.
You should use List and an iterator to cycle through the list.
You can use then use the .remove function
You are almost done!!
Integer[] ansa = new Integer[] { 0, 6, 0, 17, 1, 9, 17, 8, 4 };
for (int i = 0; i < ansa.length; i++) {
if (ansa[i] == 17) {
ansa[i] = (Integer) null;
}
}
for (Integer integer : ansa) {
System.out.print(integer+","); //0,6,0,null,1,9,null,8,4,
}
You are facing issue, Because you declared primitive I guess like,
int[] ansa = new int[] // Primitive

printing all the array value

class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.

Categories

Resources