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.
Videos
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);
I assume you want to map every value in the arr1 array to an int, and the result should be an int[] (not one int). Stream the array, map the elements to an int, and then invoke toArray. Like,
int[] numArr = Arrays.stream(arr1).mapToInt(Integer::valueOf).toArray();
Note that invoking valueOf in this way is still an example of parsing the String to an int.
Using Streams:
int[] intArray = Stream.of(arr1).mapToInt(Integer::parseInt).toArray();
Here is some untested java code. But very bad practice and bad performance... should work for you anyway ^^
public static ArrayList<Integer> getStartingWith(int[] numbers, int key)
{
ArrayList<Integer> matching = new ArrayList<Integer>();
String keyAsString = Integer.toString(key);
for(int i = 0; i < numbers.length; i++)
{
if(Integer.toString(numbers[i]).startsWith(keyAsString))
matching.add(numbers[i]);
}
return matching;
}
Take a look at @Andreas answer. Way smarter than mine!!!
If you don't want to perform any string conversions (while comparing) you can keep it to division.
public void findIfStartingWithDigit(int number){
int digits = String.valueOf(number).length();
int tmpNumber;
for (int i = 0; i < numbers.length; i++){
tmpNumber = numbers[i];
while (tmpNumber >= 10*digits){
tmpNumber = tmpNumber / 10;
}
if (tmpNumber == number){
System.out.println(numbers[i]);
}
}
}
You can use Integer.valueOf.
Integer.valueOf((String) array [i])
The Integer class has a method valueOf which takes a string as the value and returns a int value, you can use this. It will throw an NumberFormatException if the string passed to it is not a valid integer value.
Also If you are using java5 or higher you can try using generics to make the code more readable.
You can implement the same using Generics, which would be easier.
List<Integer> numbers = new ArrayList<Integer> ();
Integer[] array = numbers.toArray (new Integer [10]);
The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:
String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.
You don't need to convert int to String. Just use % 10 to get the last digit and then divide your int by 10 to get to the next one.
int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
array.add(temp % 10);
temp /= 10;
} while (temp > 0);
This will leave you with ArrayList containing your digits in reverse order. You can easily revert it if it's required and convert it to int[].
Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.
- Result: 0
- Loop 1: Result * 10 => 0, Result + 1 => 1
- Loop 2: Result * 10 => 10, Result + 2 => 12
- Loop 3: Result * 10 >= 120, Result + 3 => 123
This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.
You have to cycle in the array and add the right value. The right value is the current element in the array multiplied by 10^position.
So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....
int res=0;
for(int i=0;i<ar.length;i++) {
res=res*10+ar[i];
}
Or
for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
res+=ar[i]*Math.pow(10, exp);
Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:
Copypublic static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10);
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s, radix));
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
As for parsing with a comma, I'm not familiar with one. I would sanitize them.
Copyint million = Integer.parseInt("1,000,000".replace(",", ""));
First Question: Difference between parseInt and valueOf in java?
Second Question:
CopyNumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
Third Question:
CopyDecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);
Following code for a simple one line solution using Java 8+ with Stream and mapToInt:
Stream.of(String.valueOf(myInt).split("")).mapToInt(Integer::parseInt).toArray();
Generic solution:
import java.util.stream.Stream;
public static int[] convertValueToIntegerArray(int value) {
return Stream.of(String.valueOf(value).split(""))
.mapToInt(Integer::parseInt)
.toArray();
}
Example:
import java.util.Arrays;
public void testIntegerArray() {
int myInt = 4821;
int[] myIntArr = convertValueToIntegerArray(myInt);
System.out.println("Converted: " + Arrays.toString(myIntArr));
}
public static void main(String[] args) {
int myInt = 4821;
int size = 0;
int temp = myInt;
while(temp > 0) {
temp = temp/10;
size++;
}
int[] numbers = new int[size];
int index = 0;
while(myInt > 0) {
numbers[index] = myInt % 10;
myInt = myInt / 10;
index++;
}
for (int i : numbers) {
System.out.println("Number : "+i);
}
}
output
Number : 1
Number : 2
Number : 8
Number : 4