Java - All Elements in List Become Identical - java

I'm having trouble using a for loop to assign elements to a List. Here's the section of code I'm having trouble with:
private static List<String[]> modify(List<String[]> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String[] block = data.get(i);
// some code here to modify the contents of block
data2.add(block);
}
return data2;
}
For some reason, this method returns a List with all its elements completely identical. I've tried outputting the List elements to see where this is happening, and it seems to be happening outside of the loop. For example, this:
private static List<String[]> modify(List<String[]> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String[] block = data.get(i);
// some code here to modify the contents of block
data2.add(block);
System.out.println(Arrays.toString(data2.get(i));
}
return data2;
}
displays a list of different elements, whereas this:
private static List<String[]> modify(List<String[]> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String[] block = data.get(i);
// some code here to modify the contents of block
data2.add(block);
}
for (int i=0; i<data2.size(); i++) {
System.out.println(Arrays.toString(data2.get(i)));
return data2;
}
displays a list consisting of only identical elements. It seems to me that the elements are being correctly added to the List inside of the for loop, yet end up becoming identical. Why is this, and how can I fix it?

You should probably make a temporary string to do the manipulations, initialize your String array, then fill it up with your data and then pass it to data2 like this:
private static List<String[]> modify(List<String> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String tempString = data.get(i);
String[] block = new String[255];
// some code here to modify the contents of block
// actually fill block with data
block.add("modified data");
block.add("more manipulated data");
data2.add(block);
}
return data2;
}
Edit
This should fix the no compiling problem!

It seems strange that you have managed to make this code run at all. There is an obvious syntax error in your code:
private static List<String[]> modify(List<String> data) {
...
String[] block = data.get(i);
Your block is an array of String, whereas data.get() returns a single string. In the latter of your fragments the braces are unmatched, so it also should not get compiled. If you put '}' after System.out.println(...); and made the parameter of type List<String>[] instead of List<String>, your code would work fine.

Related

Converting array list to a string array

I've been trying to convert my string array list to a string array so I can print it but have been unable to do so.
This is the class I have, randomQuestion which takes in an array list from the gameQuestions method in the same class.
I have never tried to convert an array list using a loop before hence the difficulty, I was able to convert it fine with the code
String[] questions = data1.toArray(new String[]{});
But I need it to loop through using a for loop to store it in an array which I can then print one at a time once a question is answered successfully.
The error I'm receiving from netbeans is cannot find symbol
Symbol:methodtoArray(String[]) for the .toArray portion below.
public String[] randomQuestion(ArrayList data1) {
Collections.shuffle(data1);
for (int question = 0; question < 10; question++) {
ranquestions = data1.get(question).toArray(new String[10]);
}
return ranquestions;
}
Any help would be greatly appreciated.
You can use List.toArray(). Class List has a method:
<T> T[] toArray(T[] a);
Assuming you have an ArrayList<String>, you can use String.join(delimiter, wordList) in order to concatenate all the elements to a single String:
public static void main(String[] args) {
// example list
List<String> words = new ArrayList<String>();
words.add("You");
words.add("can");
words.add("concatenate");
words.add("these");
words.add("Strings");
words.add("in");
words.add("one");
words.add("line");
// concatenate the elements delimited by a whitespace
String sentence = String.join(" ", words);
// print the result
System.out.println(sentence);
}
The result of this example is
You can concatenate these Strings in one line
So using your list, String.join(" ", data1) would create a String with the elements of data1 delimited by a whitespace.
The question is how to create an array with only 10 elements of the list, if I understood correctly.
Streams (Java 8):
String[] ranquestions = data1.stream()
.limit(10)
.toArray(String[]::new);
Loop (based on question, avoiding unnecessary changes):
String[] ranquestions = new String[10];
for(int question = 0; question < 10; question++) {
ranquestions[question] = data1.get(question);
}
always assuming List<String> data1, if not some conversion is needed.
Example:
String[] ranquestions = data1.stream()
.limit(10)
.map(String::valueOf)
.toArray(String[]::new);
or, loop case:
ranquestions[question] = String.valueOf(data1.get(question));
You can do:
private String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
If you are sure you are getting a list of string (question) you can instead
private String[] randomQuestions(List<String> data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
Edit 1
private static String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
String[] randomQuestions = new String[data.size()];
for(int i=0; i<data.size(); i++){
randomQuestions[i] = String.valueOf(data.get(i));
}
return randomQuestions;
}

check if an ArrayList contains all Strings from another ArrayList

I need to check if all Strings from ArrayList are present in another ArrayList. I can use containsAll but this is not what I want to achieve. Let's me show you this on example:
assertThat(firstArray).containsAll(secondArray);
This code will check if all items from one array is in another one. But I need to check that every single item from one array is contained in any place in the second array.
List<String> firstArray = new ArrayList<>;
List<String> secondArray = new ArrayList<>;
firstArray.add("Bari 1908")
firstArray.add("Sheffield United")
firstArray.add("Crystal Palace")
secondArray.add("Bari")
secondArray.add("Sheffield U")
secondArray.add("C Palace")
So I want to check if first item from secondArray is in firstArray(true) than that second(true) and third(false). I wrote the code which is doing this job but it's quite complicated and I would like to know if there is any simpler way to achieve this goal (maybe with using hamcrest matchers or something like that)
ArrayList<String> notMatchedTeam = new ArrayList<>();
for (int i = 0; i < secondArray.size(); i++) {
String team = secondArray.get(i);
boolean teamMatched = false;
for (int j = 0; j < firstArray.size(); j++) {
teamMatched = firstArray.get(j).contains(team);
if (teamMatched) {
break;
}
}
if (!teamMatched) {
notMatchedTeam.add(team);
}
}
You can do something like this
List<String> firstArray = new ArrayList<>();
List<String> secondArray = new ArrayList<>();
firstArray.add("Bari 1908");
firstArray.add("Sheffield United");
firstArray.add("Crystal Palace");
secondArray.add("Bari");
secondArray.add("Sheffield U");
secondArray.add("C Palace");
Set<String> firstSet= firstArray
.stream()
.collect(Collectors.toSet());
long count= secondArray.stream().filter(x->firstSet.contains(x)).count();
///
Map<String, Boolean> result =
secondArray.stream().collect(Collectors.toMap(s->s, firstSet::contains));
If count >0, then there are some items in second array which are not there in first.
result contains the string with its status.
Thanks
If you have space concerns like you have millions of words in one file and need to check entry of second file in first then use trie. From first make trie and check every entry of second in first.
Situation:
In your question you said that you wanted to return for each element if it exists or not, and in your actual code you are only returning a list of matching elements.
Solution:
You need to return a list of Boolean results instead, this is the code you need:
public static List<Boolean> whichElementsFound(List<String> firstList, List<String> secondList){
ArrayList<Boolean> resultList = new ArrayList<>();
for (int i = 0; i < secondList.size(); i++) {
String team = secondList.get(i);
resultList.add(firstList.contains(team));
}
return resultList;
}
Demo:
This is a working Demo using this method, returning respectively a List<Boolean> to reflects which element from the first list are found in the second.
Edit:
If you want to return the list of elements that were not found, use the following code:
public static List<String> whichElementsAreNotFound(List<String> firstList, List<String> secondList){
ArrayList<String> resultList = new ArrayList<>();
for (int i = 0; i < secondList.size(); i++) {
String team = secondList.get(i);
if(!firstList.contains(team)){
resultList.add(team);
}
}
return resultList;
}
This is the Demo updated.

JAVA Get each value of arraylist

I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}

How to iterate through 2d array to split the inner array in java

I have the following 2d array:
[[Reflux Symptom Sensitivity Index (Impedance)], [Symptom Acid Nonacid All Reflux], [Regurgitate 34% 71% 36%], [Stomach pain 21% 14% 19%], [Chest pain 3% 0% 3%], [], [Reflux Symptom Association Probability (Impedance)]]
I would like to all the inner arrays apart from the first one, by whitespace so that I end up with:
[[Reflux Symptom Sensitivity Index (Impedance)], [Symptom,Acid, Nonacid, All, Reflux], [Symptom,Acid, Nonacid, All, Reflux], [Symptom,Acid, Nonacid, All, Reflux],[Chest pain,3%,0%,3%]]
I could write the following code:
ArrayList<List<String>> Arr_RSI_table2d = new ArrayList<List<String>>();
List<String> stats = Arr_RSI_table2d.get(1);
// remove() returns the object that was removed
String allStats = stats.remove(0);
String allStats2=allStats.trim();
Collections.addAll(stats, allStats2.split("\\s"));
List<String> Arr_RSI_table2d_col2 = Arr_RSI_table2d.get(2);
// remove() returns the object that was removed
String All_Arr_RSI_table2d_col2 = Arr_RSI_table2d_col2.remove(0);
String All_Arr_RSI_table2d_col2_2=allStats.trim();
Collections.addAll(Arr_RSI_table2d_col2, All_Arr_RSI_table2d_col2_2.split("\\s"));
List<String> Arr_RSI_table2d_col3 = Arr_RSI_table2d.get(3);
// remove() returns the object that was removed
String All_Arr_RSI_table2d_col3 = Arr_RSI_table2d_col3.remove(0);
String All_Arr_RSI_table2d_col3_2=allStats.trim();
Collections.addAll(Arr_RSI_table2d_col3, All_Arr_RSI_table2d_col3_2.split("\\s"));
List<String> Arr_RSI_table2d_col4 = Arr_RSI_table2d.get(4);
// remove() returns the object that was removed
String All_Arr_RSI_table2d_col4 = Arr_RSI_table2d_col4.remove(0);
String All_Arr_RSI_table2d_col4_2=allStats.trim();
Collections.addAll(Arr_RSI_table2d_col4, All_Arr_RSI_table2d_col4_2.split("\\s"));
How can I do this?
ArrayList<List<String>> myList = new ArrayList();
void loopThroghArray() {
for (List<String> list : myList) {
//outer loop
for (String string : list) {
//inner loop
}
}
}
its hard to understand your code , since you have not given even the type of your array bt here i have made a example on looping through 2dimensional array. im using a enhanced for loop to loop the first array and another enhanced for loop to iterate the 2nd array you can do the spliting inside the 2nd for loop . you might wanna try this.
You could try something like this;
for (int i = 1; i < myArray.size(); i++) {
String[] innerArray = myArray.get(i);
for (int j = 0; j < innerArray.length; j++) {
innerArray[j] = removeWhiteSpace(innerArray[j]);
}
}
You will need a helper method to remove white space:
private String removeWhiteSpace(String toTrim) {
String toRet = "";
String trimSplit[] = toTrim.split(" ");
for (String word : trimSplit) {
if (!word.trim().isEmpty()) {
toRet = toRet + word + " ";
}
}
return toRet.trim();
}
This is untested but it should work fine. Let me know how it goes.

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