Java: printing an array without Arrays.toString - java

public String[] geefAlleTemplateNamen(String[][] templateLijst){
String[] lijst = new String[templateLijst.length];
for(int i = 0; i < templateLijst.length; i++){
lijst[i] = templateLijst[i][0];
}
return lijst;
}
The code above returns an array 'lijst'.
System.out.println(geefAlleTemplateNamen(templateLijst));
With this piece of code I tried to print that array, but it prints the location of the array. I know this can be solved by importing Java.util.Arrays, but I am not allowed to do this (school project), is there any way to solve this?
Thank you!

The simplest and easiest way to do this is to throw your array into a for loop.
for (int i = 0; i < lijst.length; i++) { System.out.println(lijst[i]); }
Printing the array itself should and will print its memory location, and you'll want to access each member of the array individually instead.

Easiest solution would be,
for(String s: lijst)
{
System.out.println(s);
}

Related

Remove elements from ArrayList after finding element with specific char

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.
So;
this, is, an, arra;ylist, string
Would become:
this, is, an
I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.
Here's my code so far
public String[] removeComments(String[] lineComponents)
{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));
int index = 0;
int listLength = list.size();
for(String str : list)
{
if(str.contains(";"))
{
}
index++;
}
return lineComponents;
}
This becomes trivial with Java 9:
public String[] removeComments(String[] lineComponents) {
return Arrays.stream(lineComponents)
.takeWhile(s -> !s.contains(";"))
.toArray(String[]::new);
}
We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].
First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.
Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.
public List<String> removeComments(List<String> lineComponents, CharSequence finding)
{
ArrayList<String> aux = new ArrayList<String>();
for(String str : lineComponents)
{
if(str.contains(finding))
break;
else
aux.add(str);
}
return aux;
}
This example is just for performance and bringing back my old favorite arraycopy:
public String[] removeComments(String[] lineComponents) {
int index = -1;
for (int i = 0; i < lineComponents.length; i++) {
if ( lineComponents[i].contains(";") ) {
index = i;
break;
}
}
if (index == -1) return lineComponents;
return Arrays.copyOf(lineComponents, index);
}

using loop to concatenate elements of arrays in Java in a python like way

I am new to java. I have done python before and concatenating elements of two lists or arrays seemed easy with loop. But how to do the same with java??? For example, I have a multidimensional array:
//codes
String [][] nameAry={{"Mr.","Mrs.","Ms."},{"Jones","Patel"}};
//The output I am expecting :
Mr. Jones, Mrs. Jones, Ms, Jones, etc.
// I can do it by handpicking elements from indices, as shown in oracle documentation, but what I am looking for is a loop to do the job instead of doing:
//code
System.out.println(nameAry[0][0]+", "+nameAry[1][0]);
`
////So, is there a way to put it the way I do in python,i.e.,:
x=["Mr.","Mrs.","Ms."]
y=["Jonse","patel"]
names-[a+b for a in x for b in y]
///this gives me the following result:
['Mr.Jonse', 'Mr.patel', 'Mrs.Jonse', 'Mrs.patel', 'Ms.Jonse', 'Ms.patel']
//So, is there something like this in Java???
You can just use loops with index variables to access your array. Here I'm using i to loop through the first dimension and j for the second dimension of the string array, while assembling each pair and adding it to a list.
The part with the ArrayList is just for convenience, you can also return the strings or add them to a different data structure. Hope that helps.
Edit: Explanations
ArrayList<String> list = new ArrayList<String>();
String [][] nameAry={{"Mr.","Mrs.","Ms."},{"Jones","Patel"}};
for(int i = 0;i<nameAry[0].length;i++) {
for(int j =0;j<nameAry[1].length;j++) {
list.add(nameAry[0][i]+nameAry[1][j]);
}
}
Here's a solution using streams.
String [][] nameAry={{"Mr.","Mrs.","Ms."},{"Jones","Patel"}};
List<String> list = Arrays.stream(nameAry[0])
.flatMap(x -> Arrays.stream(nameAry[1])
.map(y -> x + y))
.collect(Collectors.toList());
list.forEach(System.out::println);
Note that the flatMap method is used here. It is used to turn each element of the first subarray into a new stream. The new stream is created by .map(y -> x + y) i.e. concatenating the names to the honorifics. All the new streams are then joined.
I think the use of a 2D array here as input is wrong.
You have correctly used 2 arrays as inputs in your Python example.
So just do the same in Java.
Cartesian product method:
public String[] cartesianProduct(String[] first, String[] second) {
String[] result = new String[first.length * second.length];
int resIndex=0;
for (int i=0; i < first.length; i++) {
for (int j=0; j < second.length; j++) {
result[resIndex] = first[i] + second[j];
resIndex++;
}
}
}
Method main:
public static void main(String[] args) {
String[] nameArr = {"Jones","Patel"};
String[] prefixArr = {"Mr.","Mrs.","Ms."};
String[] result = cartesianProduct(prefixArr, nameArr);
// Here you can print the result
}

Reusing input String[] with values from arrayList

I have the following code which sorts a mixed array of items while maintaining the position of types:
For example:
[20, "abc", "moose", 2,1] turns into [1, "abc", "moose", 2, 20]
Algorithm:
public class Algorithm {
public static String[] sortMixedArray(String[] input){
if (input.length == 0){
return input;
}
// make new arraylist for strings and numbers respectively
List<String> strs = new ArrayList<String>();
List<Integer> numbers = new ArrayList<Integer>();
// add values to the arraylist they belong to
for (String item : input){
if (NumberUtils.isNumber(item)){
numbers.add(Integer.valueOf(item));
} else {
strs.add(item);
}
}
// sort for O(nlogn)
Collections.sort(strs);
Collections.sort(numbers);
// reuse original array
for (int i = 0; i < input.length; i++){
if (NumberUtils.isNumber(input[i])) {
input[i] = String.valueOf(numbers.remove(0));
} else {
input[i] = strs.remove(0);
}
}
return input;
}
public static void main(String[] args) {
String[] test = new String[] {"moo", "boo"};
System.out.println(Arrays.toString(sortMixedArray(test)));
}
I have a two-part question:
1. Is switching between array and arraylist efficient? That is, should I have used arrays everywhere instead of arraylist if my input MUST be an array.
2. What is the best way to place arraylist items back into a array? I am checking for type, is there a better way?
1.If you do it the way you have it in your code then it's perfectly fine. If you know beforehand how many elements you will have it's better to use arrays but thats not the case in your example.
2.The best and easiest way is to use the toArray() function of the List interface.
ArrayList<String> list = ...;
String[] array = list.toArray(new String[list.size()]);
But this won't work for your code since you are merging two lists into one array. You can still improve your code a bit because you do not actually have to remove the items from the lists when putting them back in the array. This safes some computation since removing the first element from an ArrayList is very inefficient (O(N) runtime per remove operation).
for (int i = 0, s = 0, n = 0; i < input.length; i++) {
if (NumberUtils.isNumber(input[i])) {
input[i] = Integer.toString(numbers.get(n++));
} else {
input[i] = strs.get(s++);
}
}
No but it highly unlikely to matter unless you have a million of elements.
Do whatever you believe is simplest and most efficient for you, the developer.
BTW the least efficient operations is remove(0) which is O(N) so you might change that.

IndexOutOfBoundsException while adding to a list in an arraylist

I am making a program which has to sort every English word based on the first two letters. Each group of two letters has it's own list which I have to add the words into therefore I have 676 lists in total. I tried making an ArrayList of Lists to do this:
public static List<List<String>> englishWordList = new ArrayList<List<String>>(673);
Now when I try to add elements to one of the lists I get this an IndexOutOfBoundsException
private static void letterSort(String s){
//Sorts the words by the first two letters and places in the appropriate list.
String letterGet = s.substring(0,2);
for(int i = 0; i < 676; i++){
if(letterGet.equals(letterCombos[i])){
Debug(s);
Debug(letterGet);
try{
englishWordList.get(i).add(s); \\IndexOutOfBoundsException here
}catch(Exception e){
e.printStackTrace();
System.exit(0);
}
}
}
Any help with fixing this would be very appreciated, also if any more information is needed I will be more than happy to add it.
You only initialized the englishWordList, but you didn't add anything to it. Therefore englishWordList is empty and any get(int) call will throw an IndexOutOfBoundsException.
You can fill it with empty Lists the following way (also note that you set initial capacity to 673 instead of 676):
public static List<List<String>> englishWordList = new ArrayList<List<String>>(676);
static {
for (int i = 0; i < 676; i++) {
englishWordList.add(new ArrayList<String>());
}
}

Having difficulty adding elements to 2-dimensional array

I have a .txt file that looks like this:
Mathematics:MTH105
Science:SCI205
Computer Science:CPS301
...
And I have an assignment that requires that I read file and place each line into an array that should look like this:
subjectsArray[][] = {
{"Mathematics", "MTH105"},
{"Science", "SCI205"},
{"Computer Science", "CPS301"}
};
I am getting a compile error when I attempt to add the contents of the file to a 2-dimensional array:
private static String[][] getFileContents(File file) {
Scanner scanner = null;
ArrayList<String[][]> subjectsArray = new ArrayList<String[][]>();
//Place the contents of the file in an array and return the array
try {
scanner = new Scanner(file);
int i = 0;
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lineSplit = line.split(":");
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j].add(lineSplit[0]); //The type of the expression must be an array type but it resolved to ArrayList<String[][]>
}
i++;
}
return subjectsArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return null;
}
Error reads:
The type of the expression must be an array type but it resolved to ArrayList<String[][]>
I am new to multi-dimensional arrays and not sure what it is I'm doing wrong. Can someone tell me what I'm doing wrong?
Your first mistake is the selection of the type for the result: this type
ArrayList<String[][]>
represents a three-dimensional structure - a list of 2D arrays. What you need is a two-dimensional structure, e.g.
ArrayList<String[]>
So the first fix is this:
List<String[]> subjectsArray = new ArrayList<String[]>(); // Note the type on the left: it's an interface
Once this is done, the rest of the code flows by itself: you do not need the inner for loop, it gets replaced by a single line:
subjectsArray.add(lineSplit);
The final fix is the return line: you need to convert the List<String[]> to String[][], which can be done by calling toArray(), like this:
return subjectsArray.toArray(new String[subjectsArray.size()][]);
I think you are trying to use an ArrayList method on a String. I am not sure that is possible. The simplest way to do what you need I think is:
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j]=lineSplit[j];
}

Categories