This question already has answers here:
Reading a plain text file in Java
(31 answers)
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
Learning file I/O in java, but cant seem to get java to recognize this format in a text document :
A=1
B=2
.
.
.
.
Z=26
What i want is for the letters A through Z to be equal to the int counterpart, I've been able to do this in C# using this code:
var dic = File.ReadAllLines(AplhabetFile)
.Select(l => l.Split(new[] { '=' }))
.ToDictionary(s => s[0].Trim(), s => s[1].Trim());
but i can't seem to find its exact java equivalent anywhere.
Any Ideas ?
You can do the same with Streams:
Map<String, String> dic = Files.lines(Paths.get(AlphabetFile))
.map(l -> l.split("="))
.collect(Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()));
Related
This question already has answers here:
Create array of regex matches
(6 answers)
Closed 4 years ago.
I need a Groovy/Java function to search for groups in a string based on regular expression
Ex:
function("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )
should return a list ["commons-collections" , "3.2.2" , "jar"]
Python can do this by
>> import re
>> re.search("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )
>> print(result.groups())
output is ("commons-collections" , "3.2.2" , "jar")
It is a simple and basic task in groovy. Any way I hope this answer will help you.
"commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) {
println it
}
This will produce the output :
[commons-collections-3.2.2.jar, commons-collections, 3.2.2, jar]
Update :
As #tim_yates mentioned in comment,
println "commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) { it.tail() }
This provides better output than above and also more specific to the task.
Output:
[[commons-collections, 3.2.2, jar]]
This question already has answers here:
Groovy equivalent of Java 8 :: (double colon) operator
(2 answers)
Closed 4 years ago.
In java I can write
Arrays.asList("test ").stream().map(String::trim);
If I try this in groovy
Arrays.asList("test ").stream().map(String.&trim)
I get
Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.trim() is applicable for argument types: (String) values: [test ]
Possible solutions: trim(), wait(), grep(), wait(long), split(java.lang.String), print(java.io.PrintWriter)
What is the correct syntax or do I have to resort to
Arrays.asList("test ").stream().map({ x -> x.trim() })
?
you can use .map { it.trim() } too, but otherwise, groovy does not have method reference working like java one
This question already has an answer here:
Spark 2.0.0 Arrays.asList not working - incompatible types
(1 answer)
Closed 5 years ago.
I just started learning Apache Spark and doing a project. The first task is reading a file contains multiple lines of text and get a dictionary. Based on my understanding I write the following code:
JavaRDD<String> lines = spark.sparkContext().textFile("tokens.txt",10).toJavaRDD();
JavaRDD<String> dictionary = lines.flatMap(l -> l.split(" "));
I also tried
JavaRDD<String> dictionary = lines.flatMap(l -> Arrays.asList(l.split(" ")));
However Eclipse is giving me this error:
Type mismatch: cannot convert from JavaRDD<Object> to
JavaRDD<String>
What am I doing wrong?
I just figured it out. Need to call iterator() at the end.
JavaRDD<String> dictionary = lines.flatMap(l -> Arrays.asList(l.split(" ")).iterator());
This question already has answers here:
How to split a string, but also keep the delimiters?
(24 answers)
Closed 6 years ago.
I am having a string "role1#role2#role3#role4$arole" separated with delimiter # and $. I used below java code
String str = "role1#role2#role3#role4$arole";
String[] values = StringUtils.splitPreserveAllTokens(str, "\\#\\$");
for (String value : values) {
System.out.println(value);
}
And got the result
role1
role2
role3
role4
arole
But my requirement is to preserve the delimiter in the result. So, the result has to be as per requirement
role1
#role2
#role3
#role4
$arole
I analyzed the apache commons StringUtils method to do that but was unable to found any clue.
Any library class to get the above intended results?
You may use a simple split with a positive lookahead:
String str = "role1#role2#role3#role4$arole";
String[] res = str.split("(?=[#$])");
System.out.println(Arrays.toString(res));
// => [role1, #role2, #role3, #role4, $arole]
See the Java demo
The (?=[#$]) regex matches any location in a string that is followed with a # or $ symbol (note the $ does not have to be escaped inside a [...] character class).
This question already has answers here:
How do you validate a URL with a regular expression in Python?
(12 answers)
Closed 6 years ago.
I am new to Python and would like to know how to have build a regex pattern to match a URL
I have the following code in Java and it works. I need to have a similar one in python
Java:
URI uri = new URI("http://localhost:8080")
Matcher m = Pattern.compile("(.*)" + "/client" + "/([0-9]+)")
.matcher(uri.getPath());
Could someone guide me with having an equivalent regex in Python
Why not use urlparse? Batteries included :-).
>>> import urlparse
>>> urlparse.urlparse("http://localhost:8080")
ParseResult(scheme='http', netloc='localhost:8080', path='', params='', query='', fragment='')
Here's the equivalent in Python 2.7:
import re
from urlparse import urlparse
url = urlparse('http://localhost:8080')
match = re.match(r'(.*)/client/([0-9]+)', url.path)
EDIT
Here's how you would use match to get the individual components (just guessing as to what you want to do next):
if match:
prefix = match.group(1)
client_id = int(match.group(2))