How do I remove a specific string from a List that contains Strings....
As in:
ArrayList<String> myStrings = new ArrayList<>();
myStrings.add("Alpha");
myStrings.add("Beta");
myStrings.add("Gama");
. //The order can be random
.
.
.
Now , I only have the list myStrings and I don't know which String is at which index. But I know, that I want to display all the strings after removing say "Alpha".
To Summarize , How can I get the strings from a String array after removing a String that I know that array contains , but don't know its index/position.
Use remove :
myStrings.remove("Alpha");
Note that this would only remove the first occurrence of "Alpha" from your list.
boolean remove(Object o)
The above method of ArrayList class will remove the first occurence of Object o from the list.
You can do:
myStrings.remove("Alpha");
It will return true if the ArrayList contained the specified element.
Do you have duplicates in the list of String that you also wish to remove?
If so, you can convert the list of String into a set of String. Then, you can remove strings from the set efficiently, convert it back into a map.
// converting to set will remove duplicates
final Set<String> uniqueStrSet = new HashSet<String>(listOfString);
// remove string from set
uniqueStrSet.remove(strToRemove);
// convert set back to list
list = new ArrayList<String>(uniqueStrSet);
if this not work
myStrings.remove("Alpha");
try this it works fine with me
int pos = myStrings.indexOf("Alpha");//Getting string position
myStrings.remove(pos);
Related
I was able to remove an Integer from a List and store it in a variable. However, I am having troubles doing it with String. Is there a way to remove a string in a List and store it?
The code below shows how I can do it with Integers:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Integer removedItem = list.remove(3);
I did the same but this time with String but doesnt work:
List<String> list = new ArrayList<String>();
list.add("Milk");
list.add("Eggs");
list.add("Butter");
String removedItem = list.remove("Butter");
Is it possible to store something that is removed (String) ? I would appreciate any help! Thanks!
You're confusing List#remove(index) and List#remove(Object). The first example isn't actually removing the number 3, but the 4th (index 3) item in your list and returning what object it was. If you did list.remove(3) with your String list, you would get the 4th String object back. Additionally, if you already know the string you're removing, why do you need to store it again?:
String toRemove = "Butter";
list.remove(toRemove); //we already know it's "Butter"
There are actually two different methods you used.
Collection.remove(Object o) tries to remove an object and returns true if removed something (false otherwise). You use this approach in the example with List<String> and can do the same with List<Integer> if you replace Integer removedItem = list.remove(3); with Integer removedItem = list.remove(new Integer(3));
List.remove(int index) removes an element by its index in List and returns removed element. In your first example in Integer removedItem = list.remove(3); you actually used that method because you've passed an int as the argument instead of object (in that case it would be Integer).
Remember that indexes in java collections start at 0, so you'll get NullPointerException while trying to execute your first example.
I have elements that is declared in a list variable such as:
List<List<String>> textList = new ArrayList<>();
The elements are added such as:
textList.add(Arrays.asList(p)); //adding elements
The only way I could output the elements inside the variable is by using:
for(List<String> s: textList){
System.out.println(s); }
which output elements like this:
[He is a boy.]
[He likes apple.]
[She is a girl.]
Now, I would like to store them in an array so that the elements will look like this when outputted.
[He is a boy., He likes apple., She is a girl.]
I've tried
String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);
for(String s : textArr){
System.out.println(s);}
but I got an error about:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
So, how do I convert the elements inside a list into array using the proper way. Thanks!
Your problem is that you are not storing Strings in your list textList.
textList.add(Arrays.asList(p));
As the type says, you have a List of List of String here.
So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!
But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.
What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:
for (String someString : someCollection) {
System.out.println(someString);
}
someCollection can be both: array or List!
In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.
Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).
(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).
Using streams and flatMap, you can do this:
List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);
This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):
List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);
You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like
//Your list
List<List<String>> textList = new ArrayList<>();
//The iterators
Iterator<List<String>> itList = textList.iterator();
Iterator<String> itString;
//The string to store the phrases
String s[] = new String[textList.size()];
int i =0;
//First loop, this seeks on every list of lists
while(itList.hasNext()){
//Getting the iterator of strings
itString = itList.next().iterator();
s[i] = "";
//2nd loop, it seeks on every List of string
while(itString.hasNext()){
s[i] = s[i].concat(itString.next());
}
s[i] = s[i].concat(".");
i++;
}
I have the following:
[[Statistics (pH)], [ Upright Normal Recumbent Normal Total]]
I want to split the first element of the second element on whitespace so that I end up with:
[[Statistics (pH)], [Upright,Normal,Recumbent,Normal,Total]]
My code so far:
for (ArrayList<List<String>> row2 : StatspH) {
row2.get(1).get(0).split("\\s");
}
but nothing happens
Java Strings are immutable, so you need to store the return value of split("\\s") in the correct List.
I recommend something like
for (ArrayList<List<String>> row2 : StatspH) {
List<String> stats = row2.get(1);
// remove() returns the object that was removed
String allStats = stats.remove(0);
Collections.addAll(stats, allStats.split("\\s"));
}
Note that we're removing the original string first, then adding all of the 'split' values.
I want to know if there is a function in Java retrieve one string from array of strings if the other strings are the same i.e. if I have in my array :
yes,yes,yes,yes,no,no,no,no .. I want to get only one yes and one no and display them!
and not by using for loop and comparing ! , just I want to know if this function exists in Java .
Insert all those into a Set.Then u will get like that
String[] array = {"yes","yes","yes","yes","no","no","no","no"};
Set<String> mySet = new HashSet<String>(Arrays.asList(array));
Set does not allow duplicates.
Finally the set contains yes and no(only 2 elements)
If this is your array
String[] a = {"yes","yes","yes","yes","no","no","no","no"};
then this will display unique values
System.out.println(new HashSet(Arrays.asList(a)));
Dump your array into a set and use that:
Set uniqueStrings = new HashSet(Arrays.asList(yourArray));
If you need it as array again you can use
String[] uniqueStringsArray = uniqueStrings.toArray(new String[uniqueStrings.size()]);
Internally, this iterates through the array and compares the Strings. You cannot avoid that.
Try some thing like this
String[] arr=new String[]{"yes","yes","yes","yes","no","no","no","no"};
Object[] unique = new HashSet<>(Arrays.asList(arr)).toArray();
System.out.println(unique[0]);
System.out.println(unique[1]);
I have a List of string array already populated in storeInv. How do i change a specific element in the string array? For example the code below...
Thanks =]
List <String[]> storeInv ; //assume already populated with elements
String[] store = storeInv.get(5);
store[1] = 123;
store.set(5, store[1]); //this gives me an error.
List <String[]> storeInv = ...
String[] store = storeInv.get(5);
// This updates an element in one of the arrays. (You cannot
// assign an integer literal to a String or a String array element.)
store[1] = "123";
// Compilation error! 'store' is an array, so there is no 'set' method.
store.set(5, store);
// This updates an array in the list ... but in this
// case it is redundant because the 5th list element
// is already the same object as 'store'.
storeInv.set(5, store);