still a bit new with arrays and lists in java, I would like add elements to a list dynamically, so for example if I had code like this:
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(new int[] { 1, 2, 3 });
rowList.add(new int[] { 4, 5, 6 });
rowList.add(new int[] { 7, 8 });
how would I dynamically add 1,2,3,4,5,6,7 etc? thanks in advance for the help
Simply use a List<Integer> to store the numbers directly:
List<Integer> ints = new ArrayList<Integer>();
ints.add(1); // works with Java 1.5+, inboxing
ints.add(2);
Or, if you want to keep your datastructure, wrap the numbers in short arrays:
rowList.add(newValue(1));
where we have:
private int[] newValue(int a) {
int[] result = new int[1];
result[0] = a;
return result;
}
Edit
Some more Java 1.5+ magic, using varargs and autoboxing:
private int[] newValue(Integer... values) {
int[] result = new int[values.length];
for (int i = 0; i < result.length; i++)
result[i] = values[i];
return result
}
Usage:
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(newValues(10, 20, 30));
rowList.add(newValues(1,2,3,4,5,6,7));
If you want to add a new int[] to the list you will first have to create and fill it. If you don't know the length the array will be I would suggest an array that will dynamically add space as your reach its limit.
After you have created this array, just pass it as an argument. Should be straight forward.
You could use a for loop if you would like to add them without writing out every single number.
for(int i = 0; i < [however many you would like]; i++) {
ints.add(i);
}
Something of this effect (using varargs if you have JDK 5 and higher).
public class ListUtils {
public static void add(List<int[]> list, int... args) {
if (list != null && args != null) {
list.add(args);
}
}
}
Now, you can do
ListUtils.add(list, 1, 2, 3, 4, 5, 6, 7);
I am not sure of what you need but I hope this example will help you :
List<Integer> rowList = new ArrayList<Integer>();
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 1, 2, 3 }));
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 4, 5, 6 }));
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 7, 8 }));
ArraysUtils is a class of apache commons really usefull to deal with primitive and object arrays.
Regards,
Diodfr
Related
I want to sum up each i array and store it as an element of a new array.
I expect to get int[] sumUp={10,30}
What am I doing wrong?
My result is instead {0,10}
int[][] matrixOne= {{1,2,3,4},{10,20}};
int [] sumUp=new int[matrixOne.length];
int toSum=0;
for(int i=0;i<matrixOne.length;i++) {
sumUp[i]=toSum;
for(int j=0;j<matrixOne[i].length;j++) {
toSum+=matrixOne[i][j];
}
}
System.out.println(Arrays.toString(sumUp));
You're storing the result before you sum the numbers.
EDIT: forgot to reset the sum
toSum = 0;
for(int j=0;j<matrixOne[i].length;j++) {
toSum+=matrixOne[i][j];
}
sumUp[i]=toSum;
I would prefer a stream on the int[][] which you can map (and stream() to sum()) in one pass. Like,
int[][] matrixOne = { { 1, 2, 3, 4 }, { 10, 20 } };
int[] sumUp = Arrays.stream(matrixOne).mapToInt(x -> Arrays.stream(x).sum()).toArray();
System.out.println(Arrays.toString(sumUp));
Outputs (as expected)
[10, 30]
As the others are pointing out you are storing your sum in toSum not sumUp in your inner loop.
If you want to avoid these mistakes, and you are using Java 8, you could simply do something like:
int[][] matrixOne= {{1,2,3,4},{10,20}};
int [] sumUp=new int[matrixOne.length];
for(int i=0;i<matrixOne.length;i++) {
sumUp[i] = Arrays.stream(matrixOne[i]).sum();
}
You could even stream and map the outer array, but it becomes a bit more complicated.
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;
}
Is there any simple way to remove duplicate elements in Java(will two loops work and how). Thank you:)
IN: int[] arr = {1,3,4,2,3,1,6,7,7};
Output i want is:
{1,3,4,2,6,7}
the only i know is we can traverse it through loop.
eg.
for(int i = 0;i < arr.length;i++){
for(int j = 0;j<arr.length;j++){
if( ){
//what logic i can apply here.
}
}
}
This should work..
final Integer[] noDuplicates =
new LinkedHashSet<>(Arrays.asList(arr)).toArray(new Integer[0]);
Java 8 provides a nice way to do this using IntStream.
arr = Arrays.stream(arr) // Convert arr to IntStream
.distinct() // Get distinct elements (preserves order)
.toArray(); // Convert back to array
You can try this way:
int[]arr = {1,3,4,2,3,1,6,7,7};
Set <Integer> set = new HashSet<Integer>();
for ( int w: arr) {
set.add(w);
}
i think this would be helpful
public static int[] removeduplicate(int a[])
{
int count=0;
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
a[j]=-1;
count++;
}
}
}
int b[]=new int[a.length-count];
for(int i=0;i<a.length;i++)
{
if(a[i]!=-1)
{
for(int j=0;j<(a.length-count);j++)
{
b[j]=a[i];
}
}
}
return b;
}
You can use set data structure for removing duplicate elements from an array.
int arr[] = {1, 6, 4, 7, 8, 4, 7, 9, 3, 8};
Set<Integer> uniqueNumber = new HashSet<>();
for(int i = 0; i < arr.length; i++) {
//It only contains unique element
uniqueNumber.add(arr[i]);
}
For reference you can check this video tutorial https://www.youtube.com/watch?v=0HBIMjwte7s. I find it very helpful.
First u cant change the existing array , so need a new array to hold his unique numbers, again as you dont know the number of element in advance better to use ArrayList rather array. If you dont want to write to much logic or less number of loops , u can try this.
int[] arr = {1,3,4,2,3,1,6,7,7};
HashSet<Integer> hs = new HashSet<Integer>();
ArrayList<Integer> unique=new ArrayList<Integer>();
for(int num:arr){
if(hs.add(num)){
unique.add(num);
}
}
This question already has answers here:
Java Array, Finding Duplicates
(17 answers)
Closed 8 years ago.
I want to return duplicates in an array.
int[] strArray = new int[] {1,1, 2, 3, 2, 2, 3};
I have used below method to return duplicates.
private static Set<Integer> checkDuplicate(int[] intArray) {
Set<Integer> values = new HashSet<>();
for (int i = 0; i < intArray.length - 1; i++) {
if (intArray[i] == (intArray[i + 1])) {
values.add(intArray[i]);
}
else
System.out.println("not equal");
}
return values;
}
But in this way it checks only the consequtive values.And this needs huge comparisons and time consuming. So is there any better way to do this?
If you do not want to use hashing (HashSet or HashMap), you can first sort the array. And then, you can find duplicates by checking consecutive values. Overall, this method has O(n log n) time complexity.
You may try this example:
import java.util.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int[] strArray = new int[] {1,1, 2, 3, 2, 2, 3, 4, 7, 5, 4};
Set<Integer> duplicates = checkDuplicate(strArray);
System.out.printf("Duplicates: %s\n", duplicates);
}
private static Set<Integer> checkDuplicate(int[] intArray)
{
Set<Integer> duplicates = new HashSet<Integer>();
Set<Integer> tmp = new HashSet<Integer>();
for(Integer i: intArray)
{
if(!tmp.add(i))
{
duplicates.add(i);
}
}
return duplicates;
}
}
If efficiency is what you are looking for then
use HashMap that it has O(1) speed, Also iterate the array of integers in enhanced forloop because it is slightly faster than ordinary forloop
private static Set<Integer> checkDuplicate(int[] intArray) {
HashMap<Integer,Integer> values = new HashMap<Integer,Integer>();
Set<Integer> values2 = new HashSet<Integer>();
for(Integer i : intArray) //0(n)
{
if(values.get(i) != null) //O(1)
values2.add(i);
else
values.put(i, i);
}
return values2;
}
Scan your input and store each number with it's count in a Map<Interger, Integer>. Then loop over the Map and put all keys with value>1 in the resulting Set
See also here: https://stackoverflow.com/a/15217535/461499
You must have to use Collections.frequency
It uses only equals method. If you use any collection Map,Set,List which uses equals method to compare two objects as well as Has collection uses hashCode methods which takes more processing time.
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 1, 4, 4, 1, 5 };
// System.out.println(Arrays.toString(arr));
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
l.add(i, arr[i]);
}
// System.out.println(l);
Set<Integer> set = new HashSet<Integer>();
for (int j = 0; j < l.size(); j++) {
if (Collections.frequency(l, l.get(j)) > 1) {
set.add(l.get(j));
}
}
System.out.println(set);
}
O/P :
[1, 4]
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[].