I have a String, which can have an multiple number of words which are dot separated.
String s = "text.text1.text2.text3";
I want to generate a List which adds a Element for each word in the String.
List<String> list= Arrays.asList(s.split("/./")); generates just 1 Element.
Is there a fast way to do this?
String#split is the way to go here, except that you want to split on the regex pattern \. by itself, as Java's regex API does not take delimiters:
String s = "text.text1.text2.text3";
List<String> elements = Arrays.asList(s.split("\\."));
System.out.println(elements); // [text, text1, text2, text3]
Just the token is wrong, here is the correct code:
import java.util.*;
public class SeperateString {
public static void main(String[] args) {
String s = "text.text1.text2.text3";
List<String> list= Arrays.asList(s.split("\\."));
System.out.println(list);
}
}
And here is the output:
[text, text1, text2, text3]
Related
I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. How do I get rid of the square brackets???? I used a for loop and replace but it doesn't work.
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"
String[] parsed = st.split(",");
for (String next : parsed) {
next.replace("//[", "").replace("//]", "");
}
replace() works with plain Strings, not regex. Therefore you can simply use:
next.replace("[", "").replace("]", "");
Also notice that you need to assign it to some string variable; assigning it to need won't work (won't modify elements in parsed array).
You should actually remove the braces first and split later, like this:
String[] parsed = st.replace("[", "").replace("]", "").split(",");
You can do it all at one time with this regex:
(?:\D*(\d*\.\d*))+
You can do this with one line:
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
Full code:
package com.stackoverflow;
import java.util.Arrays;
import java.util.List;
public class Demo
{
public static void main(String[] args)
{
String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
for(String s : list)
{
System.out.println(s);
}
}
}
Converts string to list of strings and prints it. If you need to convert strings to doubles, use Double.parseDouble(s) in loop.
You could achieve your goal in two steps.
1) Remove all special characters except comma (,)
2) Then split by comma (,)
public static void main(String[] args) {
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");
}
Output:
I am using streams to concatenate a series of strings and add commas between them, but there must be no comma at the beginning or the end of the result string.
import java.util.Arrays;
import java.util.List;
public class QuestionNine {
public static void main(String[] args) {
new QuestionNine().launch();
}
public void launch(){
List<String> words = Arrays.asList("Hello", "Bonjour", "engine", "Hurray", "What",
"Dog", "boat", "Egg", "Queen", "Soq", "Eet");
String result = (words.stream().map(str -> str + ",").reduce("", (a,b) -> a + b));
result = result.substring(0, result.length() -1); //removes last comma
System.out.println(result);
}
}
Instead of using the String.substring() method at the end to get rid of the last comma, is there a way i could have deleted the last comma within the stream pipeline?
The usual idiom is to use the joining Collector with Streams.
String res = words.stream().collect(Collectors.joining(","));
Although you can use String.join in your case since you are directly dealing with an Iterable.
String res = String.join(",", words);
The problem with your approach is that the mapping function you apply impose that there will be a comma at the end of each word. You could get rid of this mapping; and apply the reduce function such that you get the desired output:
.stream().reduce("", (a,b) -> a.isEmpty() ? b : a+","+b);
but I don't recommend this.
Yes, you can use Collectors.joining() here:
String joined = words.stream().collect(Collectors.joining(", "));
Or, also as noted from comments, you can use newly added String.join(CharSequence, Iterable) method.
String joined = String.join(", ", words);
How can I sort values in this string based on the integral parts i.e.
Input:
[160,190];[650,790];[901,974];[401,540];[60,90];
O/p:
[60,90];[160,190];[401,540];[650,790];[901,974];
Obviously a regular sort must do in this case but I am not sure about
where should I trim the strings compare and rebuild the exact string
with optimized approach.
I'd implement the Comparator interface; a class holding both values of a pair and then:
parse the string using ';' as delimeter and put it in holder class
put all of the holder objects into a List
sort the list using the implemented comparator
Using Guava instead of reimplementing most of the necessary steps.
The first part, parsing the string and converting it to a list of integers will be much nicer, once Lambda expressions can be used.
import static com.google.common.base.CharMatcher.anyOf;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
public class StrangeSort {
public static void main(String[] args) {
String input = "[160,190];[650,790];[901,974];[401,540];[60,90]";
Splitter splitter = Splitter.on(anyOf("[],;")).omitEmptyStrings();
// This will be so much nicer with Lambda Expressions
List<Integer> list = newArrayList(transform(newArrayList(splitter.split(input)),
new Function<String, Integer>() {
#Override
public Integer apply(String arg0) {
return Integer.valueOf(arg0);
}}));
// Sort the list
Collections.sort(list);
// Print the list
String output = Joiner.on(';').join(Iterables.partition(list, 2));
System.out.println(output);
}
}
If you need to get rid of the whitespace in the output, you can print output.replaceAll(" ", "");
If each [] specifies a unique range of values, you can extract all numbers, sort them and then construct the resultant string back by grouping two elements in each [].
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(s);
Set<Integer> numbers = new TreeSet<>();
while(matcher.find()) {
numbers.add(Integer.parseInt(matcher.group(1)));
}
Next step would be to iterate over numbers and use the current and next index to form the resultant string.
An even better approach is to split the string on ; and use #Sergey N Lukin's Comparator to sort the values
String s = "[160,190];[650,790];[901,974];[401,540];[60,90];";
String[] values = s.split(";");
Set<String> sortedValues = new TreeSet<>(new TokensComparator());
sortedValues.addAll(Arrays.asList(values));
Eventually, join the set's elements with a semi-colon(;) using a loop or Google Guava's Joiner
Joiner.on(';').join(sortedValues);
The normal approach is to split the string by the delimiting character (;) and insert the elements into a sorted set (e.g., TreeSet). Then you can simply iterate over the set and join the elements into a string using the delimiter again. Since you need to sort numerically, you have to implement a Comparator and pass an instance to the TreeSet constructor.
The benefit of this approach is that there is no need for an external sort. The collection will maintain the values in sorted order so you simply iterate over the collection to recover the sorted elements.
Simple example:
import java.util.*;
public class Main {
public static void main(String[] args){
String s="[160,190];[650,790];[901,974];[401,540];[60,90]";
String[] stringArray = s.split(";");
Arrays.sort(stringArray,new TokensComparator());
String newString=Main.join(stringArray,";");
System.out.print(newString);
}
static String join(String[] stringArray, String delimiter) {
StringBuilder builder = new StringBuilder();
for (int i=0; i<stringArray.length; i++) {
builder.append(stringArray[i]);
builder.append(delimiter);
}
return builder.toString();
}
static class TokensComparator implements Comparator<String> {
public int compare(String s1, String s2) {
String token1 = s1.substring(1,s1.length()-1).split(",")[0];
String token2 = s2.substring(1,s2.length()-1).split(",")[0];
return Integer.compare(Integer.parseInt(token1),Integer.parseInt(token2));
}
}
}
I'm looking for an easy way to take a string and have all values in quotes placed into an ArrayList
Eg
The "car" was "faster" than the "other"
I would like to have an ArrayList that contains
car, faster, other
I think I might need to use RegEx for this but I'm wondering if there is another simpler way.
Using a regex, it is actually quite easy. Note: this solution supposes that there cannot be nested quotes:
private static final Pattern QUOTED = Pattern.compile("\"([^\"]+)\"");
// ...
public List<String> getQuotedWords(final String input)
{
// Note: Java 7 type inference used; in Java 6, use new ArrayList<String>()
final List<String> ret = new ArrayList<>();
final Matcher m = QUOTED.matcher(input);
while (m.find())
ret.add(m.group(1));
return ret;
}
The regex is:
" # find a quote, followed by
([^"]+) # one or more characters not being a quote, captured, followed by
" # a quote
Of course, since this is in a Java string quotes need to be quoted... Hence the Java string for this regex: "\"([^\"]+)\"".
Use this script to parse the input:
public static void main(String[] args) {
String input = "The \"car\" was \"faster\" than the \"other\"";
List<String> output = new ArrayList<String>();
Pattern pattern = Pattern.compile("\"\\w+\"");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
output.add(matcher.group().replaceAll("\"",""));
}
}
Output list contains:
[car,faster,other]
You can use Apache common String Utils substringsBetween method
String[] arr = StringUtils.substringsBetween(input, "\"", "\"");
List<String> = new ArrayList<String>(Arrays.asList(arr));
paramList = new ArrayList<String>();
paramList.add(line.split(","));
When I used this, it gives me the error:
cannot find symbol
symbol: method add(java.lang.String[])
location: interface java.util.List<java.lang.String>
With this, I would get output in this manner: "abc" "bvc" "ebf" . Now can I use trim to get rid of " ". So that the output becomes: abc bvc ebf
Input: "AAH196","17:13:00","02:49:00",287,166.03,"Austin","TX","Virginia Beach","VA"
Output: AAH196 17:13:00 02:49:00 287 166.03 Austin TX Virginia Beach VA
I need to remove the " "around the words and , between the words. I want to store this output and then jdbc will parse this data into the tables of my database on mysql.
paramList.add() wants a String but line.split(",") returns String[]
The two are not equivalent.
Maybe you want something like:
paramList = Array.asList(line.split(","));
or
paramList = new ArrayList<String>();
for(String s : line.split(",")){
paramList.add(s);
}
As for the added question, there are lots of ways to skin a cat.
If the words are ALWAYS surrounded by quotes then you can do something like:
paramList = new ArrayList<String>();
for(String s : line.split(",")){
paramList.add(s.substring(1, s.length());
}
This will remove the first and last char from the String. Which will always be the quotes.
If you need something more flexible (For instance this solution would ruin string that aren't surrounded by quotes) then you should read up on regex and java's Pattern class to see what suites your needs.
As for the solution that you provided, trim() will only remove surrounding whitespace.
import java.util.ArrayList;
class TestGenericArray {
public static void main(String[] args) {
String[] stringArray = {"Apple", "Banana", "Orange"};
ArrayList<String[]> arrayList = new ArrayList<String[]>();
arrayList.add(stringArray);
}
}