I have the following list:
List<List<int[]>> graph;
How can I print the content of graph without using loop? I tried the following 2 methods but all of them failed to print:
int[][] input=new int[][]{{1,2,5},{1,3,6},{2,3,1}};
List<List<int[]>> graph = new ArrayList<>();
for (int i = 0; i <= 3; i++) graph.add(new ArrayList<>());
for (int[] conn : input) {
int city_A = conn[0], city_B = conn[1], price = conn[2];
graph.get(city_A).add(new int[] {city_B, price});
graph.get(city_B).add(new int[] {city_A, price});
}
graph.forEach(s->System.out.println("Output:"+s));
System.out.println(Arrays.deepToString(graph.toArray()));
Output:[[I#1fb3ebeb, [I#548c4f57]
Output:[[I#1218025c, [I#816f27d]
Output:[[I#87aac27, [I#3e3abc88]
Expected output is to print each element without going to new line:
Output: [[1,2], [1,3], [2,0]]
Edit: the original question has changed.
I think what you actually want is a string representation of your graph.Have you tried a simple
System.out.println(graph);
?
Leaving the answer to the original question up, which was how to print all the integers in the inner list without using a traditional for loop.
graph.forEach(innerList -> {
innerList.forEach(s-> System.out.println("Output: "+ s))
});
But why though..
Also the forEach is just the java functional library shorthand for a traditional for loop, so I'm not quite sure what you're gaining here. Hope that helps
Try this.
graph.stream creates a stream of List<int[]>
flatmap(List::stream) takes those lists and creates a single stream of int[]
Arrays.toString takes an array and prints it separated by commas.
Note that printing an array is printing an object. Its default toString is what you see when you print it so it won't work. Arrays.toString() actually iterates over each element and returns a string that is printable.
List<List<int[]>> graph = some list;
graph.stream().flatMap(List::stream)
.forEach(arr->System.out.print(Arrays.toString(arr) + " "));
More on printing arrays
Notice the numeric part (in hex) for printing out this array. The numeric part
comes from the hashCode. Also the [I in front of the first output means a simple int array. [[I signifies an array of int arrays.
int[] arr1 = {1,2};
System.out.println(arr1); // prints [I#4617c264 on my machine
System.out.println(Integer.toHexString(arr1.hashCode()));
int[][] arr2 = {{1,2},{3,4}};
System.out.println(arr2); // prints [[I#36baf30c on my machine
Related
I want to find the first repeated character from a string. I usually do it using array_intersect in php. Is there something similar in Java?
For example:
String a=zxcvbnmz
Desired output : z
array_intersect — Computes the intersection of arrays (source)
So in this case you can use Set::retainAll :
Integer[] a = {1,2,3,4,5};
Integer[] b = {2,4,5,6,7,8,9};
Set<Integer> s1 = new HashSet<>(Arrays.asList(a));
Set<Integer> s2 = new HashSet<>(Arrays.asList(b));
s1.retainAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);
System.out.println(Arrays.toString(result));
Output
[2, 4, 5]
You can read about this here Java, find intersection of two arrays
There's no default implementation for this behavior; however, you can code your own solution! Since you want to find the first repeated character, you can make a HashSet of Characters. As you iterate through the array, you add each character to the HashSet until you come across a character already in the HashSet - this must be the first repeated character. Example code below:
public char arrayIntersect(String string) {
HashSet<Character> hashSet = new HashSet<>();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (hashSet.contains(c))
return c;
else
hashSet.add(c);
}
return null;
}
This runs in O(n) time, as HashSet lookups run in O(1) time.
Currently, I have trouble attempting to print out the individual lengths efficiently.
String[] array = {"test", "testing", "tests"};
int arraylength = array[0].length();
System.out.println(arraylength);
Now, this does work in printing out the length however, it is inefficient and doesn't work if theoretically I don't know the length of the array.
Thanks for your input and I would appreciate if the code insisted contains "System.out.println" included so I don't have trouble figuring out which to print out.
Use this:
String[] array = {"test", "testing", "tests"};
for(String str : array) {
System.out.println(str.length());
}
If you are using Java 8 then it's a one liner :)
Arrays.asList(array).forEach(element -> System.out.println(element.length()));
What you are doing is, converting your array to a list and then running a for loop over it. Then for every element, you are printing out the length of the element.
EDIT
From one of the comment, this is even a better version of my code.
Arrays.stream(array).map(String::length).forEach(System.out::println);
Here first you convert your array to a list and then map each element to the function length of string class, then you run a foreach over it which prints out the mapped values.
String[] array = {"test", "testing", "tests"};
The length for array is:
int arraylength = array.length;
To have retrieve length for string:
for(String string: array) {
System.out.println(string.length());
}
So I need to print out an array of integers. The problem is that when user enters the numbers to be processed and sorted, I do not know how many numbers there will be entered by the user. The only rule to that is that user can enter only less than 10000 numbers.
So I made an array which can hold 10000 numbers but if user enters less than 10000 numbers into the array then Array.toString() function prints out everything, even the empty spaces.
Is there any way to bypass that or are there any other methods for outputting an array in one line that would format it the output to look like this: [1, 2, 3, 4, 5, 6]
Thanks a lot!
It would be much easier to store the user's input in an ArrayList, and then just print myArryList.toString().
An ArrayList<T> (optionally <T> for generics). Is an array that dynamically adds more memory if more input comes available. The amortized cost of adding an element to such list is O(1), but it offers a convenient way to process input.
To answer your question, as #Mureinik already answered you then can use ArrayList.toString() to convert the list to a textual representation.
To answer your real question, you can do the following:
public static<T> String toStringArrayNonNulls (T[] data) {
StringBuilder sb = new StringBuilder();
sb.append("[");
int n = data.length;
int i = 0;
for(; i < n; i++) {
if(data[i] != null) {
sb.append(data[i].toString());
break;
}
}
for(; i < n; i++) {
if(data[i] != null) {
sb.append(",");
sb.append(data[i].toString());
}
}
sb.append("]");
return sb.toString();
}
And call that method with any type of array you want.
Examples
String[] names = new String[] {"Alice",null,"Charly","David",null,null};
System.out.println(toStringArrayNonNulls(names));
Integer[] primes = new Integer[] {2,3,null,null,11};
System.out.println(toStringArrayNonNulls(primes));
Object[] namesAndPrimes = new Integer[] {"Alice",2,null,3,null,"Charly",null,11};
System.out.println(toStringArrayNonNulls(namesAndPrimes));
If you want a dynamic array in Java, the best way is to learn how to use lists :
List<Integer> integers = new ArrayList<Integer>();
It prints only as many numbers as you put into it.
If you dont want to rewrite your program, this is also solution :
Integer[]x = new Integer[50];
List<Integer> integers = new ArrayList<Integer>();
integers = new ArrayList<Integer>(Arrays.asList(x));
I'm trying to achieve the following output from the following input:
Sample input:
3 4
2 1
4 5
-1
Sample output:
7
3
9
So far, I have my program doing all of the math and I'm getting it to terminate when the user puts in a negative number. My problem is that I'm having trouble getting it to print in the above format. A sample of my input/output is below:
9 9
8 8
9 -8
[18, 16]
Here's my code so far:
import java.util.ArrayList;
import java.util.Scanner;
public class sums{
public static void main(String[]args){
int addition = 0;
int previous = 0;
ArrayList<String> sums = new ArrayList<String>();
String sumsy = new String("");
for (int i=0; i<=i;){
Scanner in = new Scanner(System.in);
previous = in.nextInt();
if (previous<0){
break;
}
else {
addition = in.nextInt();
if (addition<0) {
break;
}
else {
addition += previous;
sums.add(addition+"");
}
}
} System.out.println(sums);
}
}
I believe the answer lies in somehow using a delimiter ("/n") somewhere, and getting my array of ints to print out just as strings.
I'm sorry, these small things elude me completely. Can anyone point me in the right direction?
Thank you!
-Helen
for (String sum : sums) System.out.println(sum)
use this instead of
System.out.println(sums)
System.out is a PrintStream object, and its println methods are overloaded for a variety of different types.
In this case, because sums is an ArrayList, you're calling println(Object x), which works by calling String.valueOf(x) on the passed object (which in turn calls x.toString() if x does not equal null), and printing the resulting String.
Essentially, when you pass something other than a String or a primitive to println, you're delegating the details of how it gets printed to the class of the object. In this case, since ArrayList is a library class, you have no control over this.
To make it work the way you want, you need to iterate over the values in sums, something like:
for (String someSum : sums) {
System.out.println(someSum);
}
If you're not familiar with that loop syntax, see the second half of this page: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
sums is an list of strings, not a string, so printing it isn't going to give you what you want. You have two options, you could do
for(String i : sums){ System.out.println(i); }
or you could make sums a stringbuilder and do sums.append(addition) and then System.out.println(sums.toString())
Do you really have to use an ArrayList? IMO, this makes it much more complicated than necessary. From your example input, it appears that you simply want to sum each pair of numbers. This doesn't seem to require an array. You could just add the two numbers together and immediately print out the result.
I have a brief question about how Java handles arrays. Below is my code:
//import java.util.Arrays;
import static java.lang.System.out;
public class Arrays
{
public static void main(String[] args)
{
String [][] multiArray = new String[10][8];
int k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println ();
for (int i = 0; i < multiArray.length; i++)
{
for (int j = 0; j < multiArray[i].length; j++)
{
multiArray[i][j] = i + "" + j;
out.print ("| " + multiArray[i][j] + " ");
}
out.println ("|");
}
k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println();
}
}
I understand that you have to create a double "for" loop to print out values for both dimensions and that you have to have:
multiArray[i].length
so that it knows to reference the length of the second dimension. I just don't understand how it works.
What I'm confused about is this: At the very beginning of the program, directly after I declare my array, if I write a statement like:
system.out.println (multiArray.length);
It will print the value of 10, which is the length I declared in the first dimension. If I, however, create some random variable like "int a = 0" or "int idontgetthis = 0" and then I write:
system.out.println (multiArray[a].length);
it somehow knows to print the length of the second dimension, 8. So my question is, how does it know how to do this? It's killing me!! lol
Because multiArray is really an array of arrays. So multiArray[a] is a reference to an object. That object is itself an array. That array has a length (8), and a property called length which can be used to return that length.
Basically, it is a concept confusion, by doing:
String[] array;
you are declaring that you will have an array of Strings with an unknown lenght.
A call to: System.out.println(array.length) at this moment will fail with a compilation error because array is not yet initialized (so the compiler can't know how long it is).
By doing:
String[] array = new String[8]
you declare that you will have and array of String and initialize it, specifying it will have space for 8 Strings, the compiler then allocates space for this 8 Strings.
Something important to notice is that even when the compiler now knows that you will store 8 Strings in your array, it will fill it with 8 nulls.
So a call to System.out.println(array.length) at this point will return 8 (Compiler knows the size) but a call to System.out.println(array[1]) will return a Null Pointer Exception (You have 8 nulls in it).
Now, in the example you presented, you are declaring a bidimensional array, this is, an array that will contain other arrays.
Bidimensional arrays are initialized as String[][] multiarray = new String[10][8]; and the logic is the same as in simple arrays, the new String[10][8]; indicates the lenght of the array that contains the other arrays, and the new String[10][8]; indicates the length of the contained arrays.
So doing system.out.println(multiArray[x].length); after initializing multiarray is translated as "What is the length of the Xth contained array?", which the compiler, thanks to your initialization, now knows is 8 for all the contained arrays, even when they are full of nulls at the moment.
Hope it helps to add a bit more understanding!
You could try looking at it like this.
public class Arrays{
public static class EightStrings {
public String[] strings = new String[8];
}
EightStrings[] tenOfThem = new EightStrings[10];
}