Getting a certain substring between two different delimiters based on a certain condition in java
Question
So I am not really familiar with the java String methods and I am not sure if there's an easy way to do this. I have a String which contains couple of values delimited with ":" and each couple is separated from the others by another delimiter ",". For example:
AA:BB,CC:DD,XX:YY,EE:FF
The mapping is "from" and "to" value. Based on a condition, I get the "from" value, let's take for example "XX", and I want to retrieve the "to" value in this case "YY".
I am not really sure how to do it. Any help will be appreciated.
Thanks :)
La solution
You can convert the string into a map:
String[] items = string.split(",");
Map<String, String> map = new HashMap<String, String>();
for (String item : items) {
String[] split = item.split(":");
map.put(split[0], split[1]);
}
Basically, you split the string twice. First, you break it into the individual key-value pairs by splitting it with split(",")
, then loop through all of these pairs. We split each pair once again, this time by the colon, then store the value in a key-value map which maps strings keys to string values.
You can then read a value from the map like so:
map.get(key);
For example, using your example data:
System.out.println(map.get("CC")); // prints "DD"
Autres conseils
Here is an example, how you can do this. I use Integers in my example, but you can change it really easy.
import java.util.ArrayList;
import java.util.List;
class Value {
int from;
int to;
Value(int from,int to){
this.from = from;
this.to = to;
}
//getter && setter
}
public class Test {
public static void main(String[] args) {
String input = "12:13,11:12,12:12,134:413";
String[] values = input.split(",");
List<Value> parsedValues = new ArrayList();
for(String value:values){
String[] split = value.split(":");
parsedValues.add(new Value(new Integer(split[0]).intValue(),new Integer(split[1]).intValue()));
}
}
}