I am having a Vector<String> containing some items. I want to search those items in database.
For that purpose I need to make a String consisting of comma separated items out of that Vector so that I can pass it to SQL Query.
I am doing something like this.
StringBuilder list = new StringBuilder("");
for (String items : itemList) {
if(its last element then) //How to check here
list.append(items);
else
list.append(items+",");
}
but that will return me the output like "item1,item2,item3,"
where as I want to omit the last comma (,) in case if it is last element of Vector.
I have checked Vector API and found this method lastElement() (which returns last element not boolean).
How can I check it in the loop or is there any smarter/efficient way to do it?
I would go with the String.join approach.
final List<String> itemList = Arrays.asList("item1", "item2", "item3");
final String commaSeparated = String.join(",", itemList);
System.out.println(commaSeparated); // -> item1,item2,item3
A nice and clean solution. Only available for Java 8.
This is a possible duplicate of Java: function for arrays like PHP's join()?
Don't reinvent the wheel! This has been done many many times, unit tested and maintained. so use them, don't make your own.
You can use Apache Commons StringUtils and use the join method on Iterable (which Vector is)
StringUtils.join(itemList, ", ")
Also, as pointed out by Tom in the comments of your question, in Java 8 you can use String.join()
Have a look at libraries like Google Guava
Joiner.on(",").useForNull("null").join(itemList)
Since you're using a StringBuilder, it's easier to just delete the last comma:
StringBuilder list = new StringBuilder("");
for (String items : itemList) {
list.append(items).append(',');
}
if ( list.length() > 0 ) {
list.setLength(list.length() - 1 );
}
Change your loop as below:
for (int i=0; i<itemList.size(); i++) {
list.append(itemList.get(i));
if(i != itemList.size() - 1) {
list.append(",");
}
Internally vector uses array and you are accessing element by index now instead of using advance for each loop.
There are several third party libraries that do the heavy lifting for you, like Apache Commons Lang's StringUtils:
String list = StringUtils.join(items, ',');
If you absolutely must do this yourself, I'd start with the first element and append a comma and an element for each succeeding element:
StringBuilder list = new StringBuilder();
Iterator<String> iter = items.iterator();
if (iter.hasNext()) {
// Special treatment for the first item
list.append(iter.next());
// The rest of the items
while (iter.hasNext()) {
list.append(',').append(iter.next());
}
}
Simply use,
StringUtils.join(itemList, ", ");
Related
Supposing that I have some foreach loop like this:
Set<String> names = new HashSet<>();
//some code
for (String name: names) {
//some code
}
Is there a way to check inside foreach that the actual name is the last one in Set without a counter? I didn't found here some question like this.
For simplicity and understandability, imo, would do:
Set<String> names = new HashSet<>();
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
//Do stuff
if (!iterator.hasNext()) {
//last name
}
}
Also, it depends on what you're trying to achieve. Let's say you are implementing the common use case of separating each name by coma, but not add an empty coma at the end:
Set<String> names = new HashSet<>();
names.add("Joao");
names.add("Pereira");
//if the result should be Joao, Pereira then something like this may work
String result = names.stream().collect(Collectors.joining(", "));
Other answears are completely adequate, just adding this solution for the given question.
Set<String> names = new HashSet<>();
//some code
int i = 0;
for (String name: names) {
if(i++ == names.size() - 1){
// Last iteration
}
//some code
}
There isn't, take a look at How does the Java 'for each' loop work?
You must change your loop to use an iterator explicitly or an int counter.
If you are working with a complex object and not just a plain list/set the below code might help. Just adding a map function to actually get the desired string before you collect.
String result = violations.stream().map(e->e.getMessage()).collect(Collectors.joining(", "));
Yes, there is a way to check it inside of foreach, by use of a counter:
Set<String> names = new HashSet<>();
int i = names.size() - 1;
for (String name: names) {
if (i-- == 0) {
// some code for last name
}
//some code
}
Consider, names.size() is called only one time outside of the loop. This makes the loop faster than processing it multiple times within the loop.
There is no build in method to check if the current element is also the last element. Besides that you are using a HashSet which does not guarantee the return order. Even if you want to check it e.g. with an index i the last element could always be a different one.
A Set does not guaranty order over of items within it. You may loop through the Set once and retrieve "abc" as the "last item" and the next time you may find that "hij" is the "last item" in the Set.
That being said, if you are not concerned about order and you just want to know what the arbitrary "last item" is when observing the Set at that current moment, there is not built in way to do this. You would have to make use of a counter.
.map(String::toString) from the answer above is redundant, because HashSet already contains String values. Do not use Set to concatenate strings because the order is not assured.
List<String> nameList = Arrays.asList("Michael", "Kate", "Tom");
String result = nameList.stream().collect(Collectors.joining(", "));
There is an easy way you can do this throw one condition.
consider this is your array:
int odd[] = {1,3,5,7,9,11};
and you want to print it all in one line with " - " hyphen between them except the last one.
for(int aa:odd) {
System.out.print(aa);
if(odd[odd.length - 1] != aa)
System.out.print(" - ");
}
this condition
if( odd[odd.length - 1] != aa )
will check if you aren't in the last element so you can still add " - ", otherwise you will not add it.
List<String> list = Arrays.asList("1", "2", "3");
for (String each : list) {
if (list.indexOf(each) == (list.size() - 1)) {
System.out.println("last loop");
}
}
Note: Set is NOT an ordered collection.
I am fairly new to java and would like a container that I can use to hold strings that are not empty and have them sorted.
So far, I have mostly been using ArrayList, but this seems a bit limited for this case.
Thanks
Use TreeSet or TreeMap, depending on your requirements. Both are collections that accept unique elements and keep them sorted.
A Set is what you want, as the items in it have to be unique.
As the Strings should be sorted you'll need a TreeSet.
As for the non blank Strings you have to override the insertion methods like this:
Set<String> sortedSetOfStrings = new TreeSet<String>() {
#Override
public boolean add(String s) {
if(s.isEmpty())
return false;
return super.add(s);
}
};
EDIT: Simplified thanks to Peter Rader's comment.
Thanks for all the help. Here is what I eventually came up with, using TreeSet and apache commons StringUtils. My Input is a CSV String so, I didn't use the check on the input.
String csvString = "Cat,Dog, Ball, Hedge,, , Ball, Cat"
String[] array = StringUtils.split((String) csvString, ",");
for (int i = 0; i < array.length; i++)
{
array[i] = array[i].trim(); //Remove unwanted whitespace
}
set = new TreeSet<String>(Arrays.asList(array));
set.remove(""); //Remove the one empty string if it is there
set now contains: Ball,Cat,Dog,Hedge
I have an array in Java.
I need to remove the items that are smaller than 20 characters.
Is this possible and how?
Arrays in Java are fixed-size, just like in C. You can't remove an item from it, you can only update its value. The value can also be null, which may serve your purpose.
However, it is not advised to use arrays for your use case; instead use a List implementation. ArrayList is the default choice and a LinkedList may make sense for a huge amount of additions and deletions in the middle of the list.
With Java 8, the best approach is to use the Streams API:
List<String> withLongStringsDiscarded =
myStringList.stream().filter(s -> s.length() <= 20).collect(Collectors.toList());
Use the following code, download common lang jar from apache url:http://mirror.cc.columbia.edu/pub/software/apache//commons/lang/binaries/commons-lang3-3.3.2-bin.zip
String[] arr = {"1","ab","aaa","sdfsdfew","ssdd"};
for(String s : arr){
if(s.length()>3){
arr = ArrayUtils.removeElement(arr, s);
}
}
System.out.println(ArrayUtils.toString(arr));
Iterate over each of them, check the size using .length() function, and create the array accordingly..
ArrayList<String> values = new ArrayList<String>();
for (String str : strArray) {
if (str.length() <= 20) {
values.add(str);
}
}
values.toArray();
We can use the old for loop (for(i = 0, j = 0; i<30; i++,j++)) with two variables
Can we use the for-each loop (or the enhanced for loop) in java (for(Item item : items) with two variables? What's the syntax for that?
Unfortunately, Java supports only a rudimentary foreach loop, called the enhanced for loop. Other languages, especially FP ones like Scala, support a construct known as list comprehension (Scala calls it for comprehension) which allows nested iterations, as well as filtering of elements along the way.
No you can't. It is syntactic sugar for using Iterator. Refer here for a good answer on this issue.
You need to have an object that contains both variables.
It can be shown on a Map object for example.
for (Map.Entry<String,String> e: map.entrySet()) {
// you can use e.getKey() and e.getValue() here
}
The following should have the same (performance) effect that you are trying to achieve:
List<Item> aItems = new List<Item>();
List<Item> bItems = new List<Item>();
...
Iterator aIterator = aItems.iterator();
Iterator bIterator = bItems.iterator();
while (aIterator.hasNext() && bIterator.hasNext()) {
Item aItem = aIterator.next();
Item bItem = bIterator.next();
}
The foreach loop assumes that there is only one collection of things. You can do something for each element per iteration. How would you want it to behave that if you could iterate over two collections at once? What if they have different lenghts?
Assuming that you have
Collection<T1> collection1;
Collection<T2> collection2;
You could write an iterable wrapper that iterates over both and returns some sort of merged result.
for(TwoThings<T1, T2> thing : new TwoCollectionWrapper(collection1, collection2) {
// one of them could be null if collections have different length
T1 t1 = thing.getFirst();
T2 t2 = thing.getSecond();
}
That's the closest what I can think of but I don't see much use for that. If both collections are meant to be iterated together, it would be simpler to create a Collection<TwoThings> in the first place.
Besides iterating in parallel you could also want to iterate sequentially. There are implementations for that, e.g. Guava's Iterables.concat()
The simple answer "No" is already given. But you could implement taking two iterators as argument, and returning Pairs of the elements coming from the two iterators. Pair being a class with two fields. You'd either have to implement that yourself, or it is probably existent in some apache commons or similar lib.
This new Iterator could then be used in the foreach loop.
I had to do one task where I need to collect various data from XML and store in SET interface and then output them to a CSV file.
I read the data and stored it in Set interface object as x,y,z.
For CSV file header, I used string buffer to hold the headers
String buffer
StringBuffer buffer = new StringBuffer("");
buffer.append("FIRST_NAME,LAST_NAME,ADDRESS\r\n")
Set<String> x = new HashSet<String>();
Set<String> y = new HashSet<String>();
Set<String> z = new HashSet<String>();
....
Iterator iterator1 = x.iterator()
Iterator iterator2 = y.iterator()
Iterator iterator3 = z.iterator()
while(iterator1.hasNext() && iterator2.hasNext() && iterator3.hasNext()){
String fN = iterator1.next()
String lN = iterator2.next()
String aDS = iterator3.next()
buffer.append(""+fN+","+lN+","+aDS+"\r\n")
}
I have an arraylist<string> of words. I sort it using Collections.sort(wordsList);
I'm using this array for an auto-suggest drop down box, so that when the user is typing in a letter, they are given a list of suggestions similar to what they are typing in.
How do I go about searching this array for a prefix of string, say the user types in "mount" and the array contains the word "mountain", how can I search this array and return similar values.
Here's my code so far:
public List<Interface> returnSuggestedList(String prefix) {
String tempPrefix = prefix;
suggestedPhrases.clear();
//suggestedPhrases = new ArrayList<Interface>();
//Vector<String> list = new Vector<String>();
//List<Interface> interfaceList = new ArrayList<Interface>();
Collections.sort(wordsList);
System.out.println("Sorted Vector contains : " + wordsList);
int i = 0;
while (i != wordsList.size()) {
int index = Collections.binarySearch(wordsList, prefix);
String tempArrayString = wordsList.get(index).toString();
if (tempArrayString.toLowerCase().startsWith(prefix.toLowerCase())) {
ItemInterface itemInt = new Item(tempArrayString);
suggestedPhrases.add(itemInt);
System.out.println(suggestedPhrases.get(i).toString());
System.out.println("Element found at : " + index);
}
i++;
}
return suggestedPhrases;
}
The most basic approach would be
List<String> result = new ArrayList<String>();
for(String str: words){
if(str.contains(keyword){
result.add(str);
}
}
You can improve this version, if you only concern with startWith instead of contains then you can distribute words in a HashMap and you will have narrowed search
For this task, there are better data structures than a sorted array of strings. You might look e.g. at DAWG (Directed acyclic word graph).
If wordList is fixed (does not change from one method call to the other) you should sort it somewhere else, because sort is costly, and store it in lowercase.
In the rest of the method you would do something like:
List<String> selected = new ArrayList<String>();
for(String w:wordList){
if(w.startsWith(prefix.toLower())) // or .contains(), depending on
selected.add(w); // what you want exactly
}
return selected;
Also see the trie data structure. This question has useful info. I should think its getPrefixedBy() will be more efficient than anything you can roll by hand quickly.
Of course, this will work for prefix searches only. Contains search is a different beast altogether.
As #Jiri says you can use a DAWG, but if you don't want to go that far you can do some simple and useful things.
Make use of the sorting
If you want to sort the array of words do it previously. don't sort it each time
As it's sorted you can find the first and the last word in the list that are matches. The use list.subList(from, to) to return sublist. It's a little more optimal that adding each one.
Use a pre-sorted structure
Use a TreeSet<String> for storing the strings (the will be sorted internally).
Then use treeSet.subSet(from, true, to, false);
Where from is the prefix and to is the "prefix plus one char". By example if you're looking for abc, to must be abd. If you don't want to make that char transformation anyway you can ask for treeSet.headSet(from) and iterate over it until there are no more prefixes.
This is specially useful if you read more than you write. Maybe ordering strings is a little expensive but once ordered you can find them very fast (O(log n)).
Case insensitive comparing
You can provide a Comparator<String> to the tree set in order to indicate how it must order the strings. You cam implement it or maybe there are a prebuild case-insensitive comparator over there.
Anyway its code should be:
int compare(String a, String b) {
return a.toLowerCase().compareTo(b.toLowerCase());
}
Here is a similar example:
-> http://samuelsjoberg.com/archive/2009/10/autocompletion-in-swing