How to take a delimited list, parse it, and add it to list - java

I'm using Groovy and Grails and am trying to take a parameter passed to a controller, parse it, and add each individual element into a list. I thought this would work, but it is adding the whole string into the list, leaving me with only one element.
list = []
list.add(params["firstNames"].split())
is returning a list with size 1, with the list element being a string containing all the names.
also, if I do list = params["firstNames"].split()) , it is showing a size of 2 (i have two elements) but it is still treating it as a String and I cannot perform any other list operations on it.
what is it that I'm doing wrong?
thanks for the help.

Try a variation of this:
String foo = 'foo,bar,baz'
def list = foo.split(',') as List
assert list instanceof java.util.List
assert list.size() == 3
The key part is the as List. If this doesn't work for you, make sure you're using the correct delimiter argument to split(). If you can provide us with an example of what the parameter value might be, we can probably provide a better answer.

Related

Java sets vs lists

Can someone suggest me a datatype/structure in java that satisfies:
1) no fixed size
2) does not automatically sort data. Data should be stored in the order in which it arrives
3) it should store only unique entries
4) its elements are accessible or atleast the first element should be!
links are not able to maintain unique entries.
I tried working with Sets but it changes the order of my data automatically which i dont want to let happen.
So i am now trying to work my way with LinkedHashSet, but I am not able to find the exact way to access the first element of the same for comparision.
Any suggestions please. Thanks!
You can use LinkedHashSet if you don't wanna write your own structure. Getting elements may be kinda tricky, try this:
Integer lastInteger = set.stream().skip(set.size()-1).findFirst().get();
This is gonna get the last element, if you want different elements you need to skip a different count. This is only one of the ways, you can get an iterator and iterate yourself etc. Remember to override hashCode and equals when working with sets.
LinkedHashSet is the right data structure for your requirements.
You can access the first element like so:
Set<String> set = new LinkedHashSet<>();
set.add("a");
set.add("b"); // And so on
// Retrieve first element
// Will throw NoSuchElementException if set is empty
String firstElement = set.iterator().next();
// Retrieve and remove first element
Iterator<String> i = set.iterator();
String otherFirstElement = i.next();
i.remove();
For accessing other elements, see answer from #Whatzs.
If I properly understand your question, you are looking for a data structure that would combine the properties of a Set and an ArrayList, a kind of "ArraySet".
I haven't found anything in the core java for that but it looks like the Android JDK has such a data structure.
https://developer.android.com/reference/android/util/ArraySet.html
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/util/ArraySet.java
One solution might be to build your own based on the android implementation.

How are List and List<String> different?

I'd just started working with lists and wanted to know how both of these are different?
Im guessing the second one specifically points out that it contains only string type stuff, while the first one is more flexible.
But then if the first is more flexible, why do people use the second one ever?
It's called generics.
The second one specifies this is a list of Strings and will throw a compiler error if you try to put something else.
It is useful to prevent people from putting anything besides a String in the List.
Here is a link to the java generic tutorial.
List<E> : Its generic and E will be any object i.e it will contain List of Object.
List<String> : The data type of list is string i.e it can only contain String.
It depend on the requirement what is the need of datatype of List.May be whatever example you looked require list of String.

How better convert all Set elements in java?

I have set like:
Set<String>
I need on each element of Set make split by ; and create new Set that will contain only 2-nd element. Should I make it directly one by one or exists better way?
Thanks.
If you can relax your constraint of an output being a Set<String> to being a Collection<String> you could use Guava and defer the transformation of elements until enumeration of elements through the Collections2#transform() method. You would just have to write a custom function to perform the split on an individual element.
But if you cannot/should not relax this constraint, you are best left to doing the already proposed individual iterations (as it'd be much more legible).
Code would look something like:
Set<String> input; //Given
Collection<String> output = Collections2.transform(input, new Function<String,String>() {
#Override
public String apply (String element) {
// As JohnnyO says, add appropriate edge case checking...
return element.split(";")[1];
}
});
Set<String> suffixSet = new HashSet<String>();
for (String s : inputSet) {
suffixSet.add(s.split(";")[1])
}
I'd also add appropriate error checking and handling for the case when s does not have a ; present.
As you have not shown the code, we can only guess what you're trying to do. You need to iterate through the Set and split each String. You can use split method if you want.
It is hard to say with so little information. You could iterate over the set doing split and adding to another Set.
Or you could replace Set with a e.g. HashMap and when you create the map put as key the first part of the string and as value the second so that you can retrieve the second part when you need fast.
Or if you create the strings yourself place them in different sets directly
Or...(you don't say enough) to provide more options

How to avoid using get(0) in list iteration

Is there any way by which I can avoid using get(0) in the list iteration ?
Its going to be always risky using get(0) while iterating over a list.
I know for sure that in this list I just have one object.
(P.S. I remember my last manager always saying to me to avoid using get(0) on list iteration.)
It's not really clear what you mean by "risky" but you might consider using Guava's Iterables.getOnlyElement:
List<String> foo = getListFromSomewhere();
String bar = Iterables.getOnlyElement(foo);
This makes it clear that you expect there to be one and only one element. If you think there may be no elements, you can use the overload which allows you to specify a default value.
That way your expectations are checked when you ask for the element... but it's not obvious what else you're looking for. (You remember your last manager warning you about this - but do you remember why he warned you?)
Edit: I misuderstood the question, not realizing there was only a single item in the List. While my options still work, they aren't really necessary. However, I question the danger of using get(0) if your precondition is that there is a list with a single element.
You have a few options:
First is simply let the loop get the object for you with a for-each loop
for(Object thing : things)
Second, is convert the list into another form and access it in the appropriate manner:
Object[] thingArray = things.toArray();
for(int i = 0; i < thingArray.length; i++)
Third is to use the ListIterator
ListIterator<Object> thingIterator = things.listIterator();
while(thingIterator.hasNext())
{
Object thing = thingIterator.next();
Object objOne = list.iterator().next();

Use of contains in Java ArrayList<String>

If I have an ArrayList of String forming part of a class in Java like so:
private ArrayList<String> rssFeedURLs;
If I want to use a method in the class containing the above ArrayList, using ArrayList contains to check if a String is contained in this ArrayList, I believe I should be able to do so as follows:
if (this.rssFeedURLs.contains(rssFeedURL)) {
Where rssFeedURL is a String.
Am I right or wrong?
You are right. ArrayList.contains() tests equals(), not object identity:
returns true if and only if this list
contains at least one element e such
that (o==null ? e==null : o.equals(e))
If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:
private List<String> rssFeedURLs = new ArrayList<String>();
Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.
You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?
String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}
For reference, note that the following conditional will also execute if you append this code to the above:
String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}
Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.
Perhaps you need to post the code that caused your exception. If the above is all you have, perhaps you just failed to actually initialise the array.
Using contains here should work though.
Your question is not very clear.
What's your code exactly doing? Give more code.
What's the error you're getting?
You say you get a null-pointer. You cannot get a null pointer as a value returned by contains().
However you can get a NullPointerException if your list has not been initialized. By reading your question now, I'd say that what you show here is correct, but maybe you just didn't instantiate the list.
For this to work (to add a feed URL if it isn't already in the list):
if (!this.rssFeedURLs.contains(rssFeedURL)) {
this.rssFeedURLs.add(rssFeedUrl);
}
then this declaration would do:
private ArrayList<String> rssFeedURLs = new ArrayList<String>();
or initialize your list later on, but before trying to access its methods:
rssFeedUrls = new ArrayList<String>();
Finally... Do you really need a List? Maybe a Set would be better if you don't want duplicates. Use a LinkedHashSet if preserving the ordering matters.
Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.
EDIT: Initialize your ArrayList<String> then attempt to add an item.
You're correct. As others said according to your comments, you probably did not initialize your ArrayList.
My point is different: you claimed that you're checking for duplicates and this is why you call the contains method. Try using HashSet. It should be more efficient - unless you need to keep the order of URLs for any reason.
Thanks to you all for answering so quickly. I could always use a set but I have the ArrayList working now. The problem was that in the constructor of the class containing the ArrayList, I was not saying:
public RSS_Feed_Miner() {
...
this.rssFeedURLs = new ArrayList<String>();
...
}
D'Oh! for a Friday afternoon.
ArrayList<String> newlyAddedTypes=new ArrayList<String>();
.....
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test2");
if(newlyAddedTypes.contain("test"){
//called here
}
else{
}

Categories

Resources