I am new to Java. I have one array with values but I want to print the values with id that mean{"id":1} My array with values are
int[] arr={1,2,3,4,5};
I want to print output values like below
{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}
Is it possible in Java?
You can iterate over the array and just
int[] arr = {1,2,3,4,5};
for(int a : arr){
System.out.println("{id:" + a + "}");
}
Where "a" is a short life variable that takes the value of each element in the array "arr"
This way you can print {id:1} with this short code.
You can do as follow :
int[] arr = {1,2,3,4,5};
String id = "\"id\"";
for(int i = 0 ; i <=arr.length; i++){
System.out.println("{"+id+": " + arr[i] + "}");
}
Here's the way to do it in recent Java versions (8 or higher)
System.out.println(
Arrays.stream(arr) // stream over int array
.mapToObj(i -> "{\"i\":" + i + "}") // convert int to custom String
.collect(Collectors.joining(", ")) // join Strings using a comma
) // print the big string
Related
I am trying to combine two arrays in Java, one with strings and another with integers:
int [] intArray = {1, 2, 3};
String [] strArray = {"Hello", "World"};
I am trying to get two results like following:
Object [] combinedObjects = {1, 2, 3, "Hello", "World"};
String [] combinedStrings = {"1", "2", "3", "Hello", "World"};
Edit: your question was changed after I posted my answer and it seems a more fitting answer has been posted, Instead of deleting my
post i'm going to leave the last bit here in case you need to do any
conversion from your joined array later in your project.
You also have the option to parse your data (this may be useful to you if you ever want to get the int's back from your array.
int tempInt = Integer.parseInt(tempString);
or alternatively:
String tempString = String.valueOf(tempArray[i]);
A good reference for changing types can be found at javadevnotes
you have two approachs :
1 - using arrayList:
ArrayList a = new ArrayList();
for(int i = 0 ; i < intArray.length ; i++)
a.add(intArray[i]);
for(int i = 0 ; i < strArray.length ; i++)
a.add(strArray[i]);
now you have answer in ArrayList
2 - use String.valueof() method :
String combinedStrings[] = new String[strArray.length+intArray.length];
int index= 0;
for(int i = 0 ; i < strArray.length ; i++)
combinedStrings[index++] = strArray[i];
for(int i = 0 ; i < intArray.length ; i++)
combinedStrings[index++] = String.valueOf(intArray[i]);
now you have answer in combinedStrings array
If you are not stucked to very old java version there is seldom a good reason to use Array. Especially if you want to operate on the array, enlarge or reduce it. The java collection framework is far flexibler. Since java8 the introduction of streams on collections offers a wide range of operations in a very compact coding.
Using streams I would solve your problem as following:
Object [] combinedObjects = Stream.concat(
Arrays.stream( intArray).boxed(),
Arrays.stream( strArray))
.toArray(Object[]::new);
String [] combinedStrings = Stream.concat(
Arrays.stream( intArray).mapToObj( i -> "" + i),
Arrays.stream( strArray))
.toArray(String[]::new);
If your input and your desired output should be a Collection then the code would appear even a little shorter:
Collection<Object> combined = Stream.concat(
intCollection.stream(),
strCollection.stream())
.collect( Collectors.toList() );
You should to convert the Integer values to String to solve your problem, because the Array can have one type of information :
public static void main(String args[]) {
int[] intArray = {1, 2, 3};
String[] strArray = {"Hello", "World"};
String[] combinedStrings = new String[intArray.length + strArray.length];
int i = 0;
while (i < intArray.length) {
//convert int to string with adding an empty string
combinedStrings[i] = intArray[i] + "";
i++;
}
int j = 0;
while (j < strArray.length) {
combinedStrings[i] = strArray[j];
i++;
j++;
}
for (String val : combinedStrings) {
System.out.println(val);
}
}
You can learn more about arrays in Oracle tutorial, part Creating, Initializing, and Accessing an Array
Ok so, you can create an array(EX: String[]) that holds a single value for each index by using length(), but that cannot be used for an array(EX: String[][]) that holds multiple values.
How would I pull the amount of indexes in the second mentioned array?
For 2d array
String[][] a=new String[4][5];
a.length // will give row count
a[0].length // will give column count of row 0 you can change the index for other columns
Demo
The same way:
String[][] aa = // ...
System.out.println("aa has " + aa.length + " indices");
for(int i = 0 ; i < aa.length ; ++i) {
System.out.println("aa[" + i + "] has " + aa[i].length + " indices");
}
To get the length of the array, you can do the same as you used to.
But if you want to get the amount of String objects, you can do something like this:
Stream.of(array).mapToInt(a -> a.length).sum()
I am trying to learn java by myself. I know this is probably a really easy question for most of you, but I am confused. So lets say I have a list of scores of people, say a, b, c, d who received 4, 2, 3 and 1 in a test.
So I have:
public static void main(String[] arguments) {
String[] names = { "a","b","c","d" };
int[] times = { 4,2,3,1};
How do I write the code in order to find the highest score and the second highest score?
Thanks load in advance.
Use Arrays.sort().
{
Arrays.sort(times);
System.out.println(times[times.length-1]);
System.out.println(times[times.length-2]);
}
View a live code demo.
You can go for a very simple technique Bubble Sort for sorting your array in descending order
Something like,
for(int i=0; i<array.length; i++) {
for(int j=0; j<array.length-1-i; j++) {
if(array[j].compareTo(array[j+1])>0) {
t= array[j];
array[j] = array[j+1];
array[j+1] = t;
}
}
}
Demo
EDIT
For Lambda Expression I would suggest you to first go through this document and first try it your self. If you face any problem then let us know here.
use the Array.sort method on your array, and then use the indexes. When it is sorted this way it is in ascending order.
Arrays.sort(times);
int highest = times[times.length-1]; // arrays start at index 0, so "-1"
int secondhighest = times[times.length-2];
How to accomplish this in Java 8
Code:
Integer[] numbers = {2,4,3,1,5,6,8,7};
List<Integer> N = Arrays.asList(numbers);
System.out.print("the list ");
N.forEach((i)->System.out.print(i + " "));
System.out.println();
Comparator<Integer> byThis = (i, j) -> Integer.compare(
i,j);
System.out.print("the ordered list ");
N.stream().sorted(byThis).forEach(i->System.out.print(i+" "));
System.out.println("");
String[] names = {"c", "b", "a", "d"};
for(String st: names) System.out.print(st + " " );
System.out.println();
List<String> S = Arrays.asList(names);
S.stream().sorted().forEach(s -> System.out.print(s + " "));
System.out.println("\n The Max Number is " + N.stream().max(byThis).get());
Output:
the list 2 4 3 1 5 6 8 7
the ordered list 1 2 3 4 5 6 7 8
the list c b a d
the ordered list a b c d
The Max Number is 8
Source:
http://www.leveluplunch.com/java/tutorials/007-sort-arraylist-stream-of-objects-in-java8/
http://www.dreamsyssoft.com/java-8-lambda-tutorial/comparator-tutorial.php
I have this 3x1 array/matrix in java. How can i use any one of the single components of the array. Lets say i want to
r = Math.pow(second row component,2) + Math.pow(third row component,2)
What is the calling code for the components?
Thanks
Use a foreach to iterate through the array, and then add Math.Pow index by index
double[] myArray = { 1.2, 16.5, 20.0 }
double r = 0;
for(double d : myArray)
{
r+= Math.pow(d,2);
}
If by components you mean elements, then the syntax is as follows:
int[] numbers = {1,2,3,4,5};
int num = numbers[0];
System.out.println("Number: " + num);
// Outputs Number: 1
Extra Reading
You should read the documentation. This contains all of the information you need to use the array type in Java.
If you want to access an element of an array, apend the index of the element in brackets:
r = Math.pow(second row component,2) + Math.pow(third row component,2)
becomes
r = Math.pow(arrayVariable[1],2) + Math.pow(arrayVariable[2],2)
Remember, array indexes are base zero.
I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I#3e25a5
Now my questions are:
How to display the correct value i.e. 1 2 3.
How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Use Arrays.toString( arl.get(0) ).
arl.get(0)[1]
The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!
In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.
The answer to your first question is therefore
System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );
If you're looking for particular elements, the returned int[] object must be referenced as such.
The answer to your second question would be something like
int[] contentFromList = arl.get(0);
for (int i = 0; i < contentFromList.length; i++) {
int j = contentFromList[i];
System.out.println("Value at index - "+i+" is :"+j);
}
You have to use <Integer> instead of <int>:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.
For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.
java.util.Arrays.toString() converts Java arrays to a string:
System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));
ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;
for(int i = 0; i <= list.size(); i++){
System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
number = input.nextInt();
list.add(number);
if(number == -1){
list.remove(list.size() - 1);
break;
}
}
System.out.println(list.toString());
for(int i: list){
System.out.print(i + " ");
total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);
Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.
List<Integer> integerList = IntStream.range(0,100)
.boxed()
.toList();
This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.