I have a combobox which stores "Computer ,Code:21","History ,Code:31" and also the number of items can be changed.but when I write this code for getting its items:
List<String> bIHELessons = new ArrayList<String>();
for (int i=0;i<jComboBox1.getItemCount();i++) {
String lessons = (String) jComboBox1.getItemAt(i);
if (lessons != null&& lessons.trim().length()!=0) {
bIHELessons.add(lessons);
System.out.println(bIHELessons.toString());
}
}
it will show these sentences in the console:
[Computer,Code=21]
[Computer,Code=21, History,Code:31]
Because you are appending to the list with bIHELessons.add(..). Each subsequent call adds on to the already printed string.
If you want to still add to the ArrayList and print the current item that is in the ArrayList, then use System.out.println(bIHELessons.get(i)); rather than using what you are now. I also don't think you need to use toString() because your objects are already in the type string.
Change System.out.println(bIHELessons.toString()); to System.out.println(lessons); if you only want to print the string you are currently iterating on.
From what I can see your code is doing what it should be doing. Are you wanting to know why you are seeing all items repeated with each additional call to the print screen?
That is happening because the toString() method of the List is putting all the items in the list into a single string.
I don't think the problem is with JComboBox but rather with your expectations. System.out.println(bIHELessons.toString()); will print out the entire contents of the bIHELessons ArrayList. Since you're adding a new String to the ArrayList on each iteration, it's logical that your System.out.println(bIHELessons.toString()); would show a progressive accumulation of content.
Your question isn't clear but you may consider moving the System.out.println outside of your loop and determining if that's what you're looking for.
You are printing out the ToString() representation of your entire list. If you want to print out the object you could just print out the lessons variable instead.
Related
Question: Is there an effective and efficient way to return a list of Strings that show up in a message given a list of words using Stream/Parallel Stream?
Let's say I have 'ArrayList banWords' which contains a list of words players cannot say. Now let's assume 'message' represents the message a player types. How would I check to see if 'message' contains any words in 'banWords' and if so, return all the words that appear in 'message' using Stream?
I'm asking this since I'm not very familiar with Stream and haven't found a suitable question that has been asked in the past. Currently, the code loops through every word in 'banWords' and checks if 'message' contains that word. If so, it gets added to a separate ArrayList.
for (String word: banWords)
if (message.contains(word))
// Adds word to a separate arraylist
However, I'm trying to see if there's a way I can use Stream or Parallel Stream to return the words. This is the closest I've found
if (banWords.parallelstream().anyMatch(message::contains) {
// Adds the word to another list using banWords.parallelstream().filter(message::contains).findAny().get()
}
However, that only returns the last word that appears in banWords. For example, if banWords contains 'hello' and 'hey' and the message is 'hello hey,' instead of adding "hello" and "hey" as two separate words, it just adds "hey."
Any ideas on how I can effectively get a list of words in message? At this point, I'm looking for the most effective or quickest way to do this so if you have another way that doesn't use Streams, I would be happy to hear.
Suppose of you have a String ArrayList banWords then create stream using that string, and use filter to filter strings that contains banWords
List<String> list = Stream.of("ArrayList banWords").filter(s->s.contains("banWords"))
.collect(Collectors.toList());
You can create stream with multiple strings also
List<String> list = Stream.of("ArrayList banWords","Set banWords", "map").filter(s->s.contains("banWords"))
.collect(Collectors.toList());
So this is how you need to do
List<String> list = word.stream().
.filter(s->message.contains(s))
.collect(Collectors.toList());
message.stream().filter(s -> bannedWordSet.contains(s)).collect(Collectors.toList());
Something to note, it's important to use a set for your list of banned words instead of a list. It'll be much more efficient.
you can collect to list after filter()
List foundWords = banWords.parallelstream().filter(message::contains).collect(Collectors.toList());
I'm French so excuse my English not necessarily correct.
I explain the context, I currently have a String array list named "tempCustomerDrugsIdsList" (var1) and another string array list named "tempDrugsTableList"(var2).
When I make a loop "For" on "var1" then another one in "var2","var2" loses its format, i. e. upper case is replaced by lower case and spaces are deleted.
I tested with another loop with the same type of variables (but empty), the result being the same I think the problem comes from my way of using java. Being on vb. net before, I must have taken some bad habits !
I don't know how to solve this problem, I've only been working in java for 2 weeks.
Thank you for helping me.
[EDIT]
My problem was:
List<String[]> tempDrugsTableList = otherList;
But this code doesn't duplicate the list.
AxelH gave me the following solution:
List<String[]> tempDrugsTableList = new ArrayList<String[]>(otherList);
Well, you are not doing a "copy" of the list
tempDrugsTableListCopy = tempDrugsTableList; // Get copy of original tempDrugsTableList for comparate
but sharing the reference, every update done in the tempDrugsTableListCopy will be done in the original list (same reference, same adress in memory). Since you are updating that copy in the following loops ... you update the original list too. What you want is to clone the list.
You could do it simply with copyList = new ArrayList(originalList); or for a deep clone, you need to iterate each element to duplicate those. (array need to be duplicated too if you change the value in those)
"String[]" tmpCustomerIds means you are getting a string array from a string array, which you would be using in a 2d array. Try it with just "String" in the for each loops. I am assuming you are using 1d arrays in this case.
I am trying to use the libgdx List widget to make a list of all the items in an arraylist. Well, actually my arraylist is a list of objects, and each of the objects contains a string that is the objects "name".
However, when I try to show these with a List, it lists them horizontally, not vertically. If I try to show the contents of a normal array it lists the contents vertically. I am implementing Screen in my classes.
For example,
ArrayList<String> PartyListEntries = new ArrayList<>();
private List PartyList = new List(skin);
PartyListEntries.add("ham");
PartyListEntries.add("hag");
PartyListEntries.add("ham");
PartyList.setItems(PartyListEntries);
table.setFillParent(true);
table.top().left().padTop(10).padLeft(10);
table.add(PartyList);
stage.addActor(table);
This shows: [ham, hag, ham]
But if I make a String array and have the array contents be { "ham", "hag", "ham" }
then it shows
[ham]
[hag]
[ham]
horizontally(without the line breaks).
This is my first issue with list. My 2nd issue is that when string values are the same, it selects both of them. In the 2nd example, if I set the default selection to index zero it will put both index 0 [ham] and index 2 [ham] as selected. It will do this for every string that has the same value as whatever is selected. I.. don't want it to do this. I want them to be treated as unique since they are.
I am trying to look at the code for List but to be honest it's kind of beyond me. I don't know what causes these problems. I could really try to figure it out and I might and it will take me a long time, but I figure maybe you guys already know what is causing this. Or maybe can just offer me a good alternative to List.
Thanks!
Regarding the first question: the Libgdx widget just uses the toString method of whatever object you give it to make the text label. So that's why you get different results with lists and String arrays. It was just the preference of whomever wrote each of those classes how to format the array to a String. If you want to use the List class, you could subclass it and change the toString method to the way you want it, or you could create a List wrapper class that does its own method of converting the list to a String.
Regarding the second question: This is a peculiarity of Java. If you hard code strings (put them in your actual code in a class with quotation marks), then the compiler makes all matching strings into a single shared instance of the String class. So "ham" and "ham" are the same instance of String, the same object.
You can get around this by wrapping your string with a String constructor like this. new String("ham"). This will force it to create a separate instance of String.
Example:
String s0 = "a";
String s1 = "a";
String s2 = new String("a");
boolean b0 = s0.equals(s1); //evaluates true
boolean b1 = s0.equals(s2); //evaluates true
boolean b2 = s0==s1; //evaluates true
boolean b3 = s0==s2; //evaluates false
If you load your strings in from a file at runtime, matching strings will be different instances.
I'm trying to 'add' to my String[].
I'm reading a file with a BufferedFileReader. I have my code set up to return a String[], lets call it list. Essentially my code loops through the file until it's empty (well null), adds each line to a string, then out of the loop I split() the string into my list.
I fear that because I do that the list has an immutable size, which is why I'm getting the Exception thrown.
How do I go about writing the following code the 'correct' way?
Code
note the list below isn't instantiated like that, just for labeling purposes.
String[] list;
int length = list.length;
list[length + 1] = (method that returns a string);
list[length + 2] = (method that returns a string);
It goes on for 5 spaces.
I'm going about this because I'm attempting to save fields to a file, and in order to avoid overwriting a file I'd like to add to it instead.
TL;DR:
Essentially trying to add to a String[] or find a better alternative because I can't change the length.
Your question is not so Clear.
If I am correct you want to define array size by dynamically
You better use java.util.ArrayList .. Where you can dynamically change the length of the Array .
String[] or find a better alternative because I can't change the
length.
You better use ArrayList for this.
ArrayList<String> ar=new ArrayList<String>(put capacity if you want);
you can remove search in arraylist easily.
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
return list.toArray();
My program produces a list of Strings in one activity, then passes it to another activity, and the second activity uses the strings.
When I test by printing out each element of the list at the beginning of the second activity, the printout looks perfect. For example, if I am hoping for the list to contain "Lemon Juice", it prints out exactly right, but yet the logic in the second activity still doesn't work. If I add "Lemon Juice" just like that to the list manually, the logic in the second activity works fine, so the issue is that somehow the string in the received List is not really "Lemon Juice". But:
It prints out exactly correctly (including checking for spaces in front and at the end).
I have tried explicitly casting the received list elements as (String) just to be sure they are Strings.
If I run "Lemon Juice".contains(received String) it comes back true, and if I run received String.contains("Lemon Juice") it
comes back true, but if I run received String.equals("Lemon Juice") it comes back false. This is very confusing to me.
Can anyone think of a possible explanation for how something that is cast as a string, prints as a string, and looks like a string, is not performing like a string?
EDIT to include some code as requested:
// instance variable at top of class--list to which strings will be added for use in
// 2nd activity
private List<String> exs = new ArrayList<String>();
// get array of strings from extra from intent from first activity
String[] recExs = getIntent().getStringArrayExtra(BrowseActivity.EXS);
for (int exx = 0; exx < recExs.length; exx++) {
String curEx = (String) recExs[exx];
exs.add(curEx);
}
Somehow, when I pass exs to the method I need to use the strings, it doesn't work, even though, as explained above, printing and calling contains etc all show that the string, before I added it to exs, was at I wanted it to be.
It's hard to help when you only posted a small snippet of your code.
But I'm guessing the reason String.contains works but String.equals doesn't is that maybe there is space in the Strings. Try String.trim on both side of the Activity when passing and receiving data.