Get value of a param in a string using java - java

I have string variable String temp="acc=101&name=test"; and now how to get the value of name param from temp string.

temp.split("&")[1].split("=")[1]

public static Map<String, String> getParamMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
String temp="acc=101&name=test";
Map<String, String> map = getParamMap(temp);
for(Object object :map.keySet()){
System.out.println("key= "+object +" value= "+map.get(object));
}
System.out.println(map.get("name"));

Here is a non-general way
String str = "name=";
System.out.println(temp.substring(temp.indexOf(str) + str.length()));
It could be implemented in more general way of course:
String temp = "acc=101&name=test";
StringTokenizer st = new StringTokenizer(temp, "&");
String paramName = "name";
String paramValue = "";
while(st.hasMoreElements()) {
String str = st.nextToken();
if (str.contains(paramName)) {
paramValue = str.substring(str.indexOf(paramName) + paramName.length() + 1);
break;
}
}
System.out.println(paramValue);

You can use a method like below
public static String getValue(String queyStr, String paraamName){
String[] queries=queyStr.split("&");
for(String param:queries){
if(param.indexOf(paraamName)!=-1)
return param.split("=")[1];
}
return null;
}
And call the method like
getValue(temp, "name")

public static void main(String[] args)
{
String temp = "acc=101&name=test";
System.out.println(temp.split("&")[1].split("=")[1]);
}

If you are looking for a way to parse GET-Parameters out of an URL:
public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = url.getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
return query_pairs;
}
You can access the returned Map using <map>.get("name"), with the URL given in your question this would return "test".

Assuming you have constant format :
String temp="acc=101&name=test";
String result =temp.substring(temp.lastIndexOf("=")+1,temp.length());
//result is test

String temp="acc=101&name=test";
String[] split = temp.split("&");
String[] name = split[1].split("=");
System.out.println(name[1]);

I would put the whole parameter in a HashMap so it is easy to get the values.
HashMap<String, String> valuemap = new HashMap<String, String>();
If you do it like so, you have to split the values at the right place...
String temp="acc=101&name=test";
valuemap.put(temp.split("&")[0].split("=")[0], temp.split("&")[0].split("=")[1]);
valuemap.put(temp.split("&")[1].split("=")[0], temp.split("&")[1].split("=")[1]);
...and put them into your HashMap. Than you have a nice collection of all your values and it is also better if you have more than only that two values. If you want the value back, use:
valuemap.get("acc")
valuemap.get("name")

Related

Java guava Splitter failing when there are duplicate keys

How we can handle duplicate keys while using java guava Splitter function. Here is the sample code which is encountering the following issue. Is there a better way to handle this issue.
String fieldSplit = " ";
String valueSplit = "=";
String message = "ip=1.2.9.0 error=NA ip=1.2.9.0";
Map<String, String> parserMap = Splitter.on(fieldSplit).omitEmptyStrings().withKeyValueSeparator(valueSplit).split(message);
Exception in thread "kv-plugin-ac801a38-66f1-4ffe-86ca-f9eb6c823842-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000, topic=kv-input, partition=0, offset=22, stacktrace=java.lang.IllegalArgumentException: Duplicate key [ip] found.
Im getting the above error. Can somebody suggest a better way to handle this. Since im new to java.
Depends on what you want to do with the duplicate keys.
Map<String, String> is a key value storage that can have only unique keys and only one value.
If you want to store all those values you would need something like Map<String, List<String> or Guava Multimap.
In this case you cannot do this with the Splitter as it cannot handle duplicate keys. You would need to write the logic by yourself.
String fieldSplit = " ";
String valueSplit = "=";
String message = "ip=1.2.9.0 error=NA ip=1.2.9.0";
Map<String, List<String>> parserMap = new HashMap<>();
for (String part : message.split(" ")) {
String[] subparts = part.split("=", 2);
if (!parserMap.contains(subparts[0])) {
parserMap.put(subparts[0], new ArrayList<>());
}
parserMap.get(subparts[0]).add(subparts[1]);
}
If you want to omit those duplicate entries you can still use the Map<String, String> with something like this.
Map<String, String> parserMap = new HashMap<>();
for (String part : message.split(" ")) {
String[] subparts = part.split("=", 2);
if (!parserMap.contains(subparts[0])) {
parserMap.put(subparts[0], subparts[1]);
}
}
Throwing on a duplicate key is a documented behavior of MapSplitter#split, so depending on what you want, you have to write your own "key-value" spliter consisting of two splitters. Please look at examples below, you can collect results to map with desired behavior (overwrite or discard) or even try out collecting to ListMultimap, but it makes result's values being stored in lists, even if there's only one value.
public class SO66139006 {
private static final Splitter PAIRS_SPLITTER = Splitter.on(' '); // .trimResults().omitEmptyStrings() if necessary
private static final Splitter KEY_VALUE_SPLITTER = Splitter.on('=').limit(2);
#Test
public void shouldOverwriteValuesOnDuplicateKey() {
//given
String message = "ip=42.42.42.0 error=NA ip=1.2.9.0";
//when
Map<String, String> result = parseOverwritingValues(PAIRS_SPLITTER, KEY_VALUE_SPLITTER, message);
//then
assertThat(result) // {ip=1.2.9.0, error=NA}
.containsExactly(entry("ip", "1.2.9.0"), entry("error", "NA"));
}
private Map<String, String> parseOverwritingValues(Splitter pairsSplitter, Splitter keyValueSplitter, String message) {
return Streams.stream(pairsSplitter.split(message))
.map(keyValueSplitter::splitToList)
.collect(toImmutableMap(
list -> list.get(0),
list -> list.get(1),
(oldValue, newValue) -> newValue
));
}
#Test
public void shouldDiscardValuesOnDuplicateKey() {
//given
String message = "ip=42.42.42.0 error=NA ip=1.2.9.0";
//when
Map<String, String> result = parseDiscardingValues(PAIRS_SPLITTER, KEY_VALUE_SPLITTER, message);
//then
assertThat(result) // {ip=42.42.42.0, error=NA}
.containsExactly(entry("ip", "42.42.42.0"), entry("error", "NA"));
}
private Map<String, String> parseDiscardingValues(Splitter pairsSplitter, Splitter keyValueSplitter, String message) {
return Streams.stream(pairsSplitter.split(message))
.map(keyValueSplitter::splitToList)
.collect(toImmutableMap(
list -> list.get(0),
list -> list.get(1),
(oldValue, newValue) -> oldValue
));
}
#Test
public void shouldAppendValuesOnDuplicateKey() {
//given
String message = "ip=42.42.42.0 error=NA ip=1.2.9.0";
//when
ListMultimap<String, String> result = parseMultipleValues(PAIRS_SPLITTER, KEY_VALUE_SPLITTER, message);
//then
assertThat(result.asMap()) // {ip=[42.42.42.0, 1.2.9.0], error=[NA]}
.containsExactly(entry("ip", ImmutableList.of("42.42.42.0", "1.2.9.0")), entry("error", ImmutableList.of("NA")));
}
private ListMultimap<String, String> parseMultipleValues(Splitter pairsSplitter, Splitter keyValueSplitter, String message) {
return Streams.stream(pairsSplitter.split(message))
.map(keyValueSplitter::splitToList)
.collect(toImmutableListMultimap(
list -> list.get(0),
list -> list.get(1)
));
}
#Test
public void shouldThrowByDefault() {
//given
String fieldSplit = " ";
String valueSplit = "=";
String message = "ip=1.2.9.0 error=NA ip=1.2.9.0";
//when
final Throwable throwable = catchThrowable(() -> Splitter.on(fieldSplit).omitEmptyStrings().withKeyValueSeparator(valueSplit).split(message));
//then
assertThat(throwable)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Duplicate key [ip] found.");
}
}

Improper output while filtering a hashmap

I have a hashmap which has key and value in String. The data is in the form of (table1, "table1:ssn1,ssn2,ssn3"). The table name in key is of the source table name and table name in the value is of the destination table name along with the corresponding source systems names separated by a ":".
I am trying to pass source system names in arguments from the command line to filter out the key and value along with the received source system name.
I came up with the following code so far:
public class FilterKeyValues {
public static void main(String[] args) {
String[] valArr;
String ky;
Map<String, String> hmap = new HashMap<String, String>();
Map<String, String> filtered = new HashMap<String, String>();
hmap.put("Table1", "Table1:SSN1,SSN2,SSN3,SSN4,SSN5");
hmap.put("Table2", "Table2:SSN1,SSN4,SSN2,SSN5,SSN8,SSN9,SSN10");
hmap.put("Table3", "Table3:SSN4,SSN1");
hmap.put("Table4", "Table4:SSN5,SSN6,SSN7");
hmap.put("Table5", "Table5:SSN8,SSN1,SSN5,SSN2");
if(args.length > 0) {
for(String ssname: args) {
for (Entry<String, String> entry : hmap.entrySet()) {
if (entry.getValue().contains(ssname)) {
ky = entry.getKey();
valArr = entry.getValue().split(":");
filtered.put(ky, valArr[0]+":"+ssname);
}
}
}
}
for (String iter: filtered.keySet()){
String key = iter.toString();
String value = filtered.get(key).toString();
System.out.println(key + "->" + value);
}
}
}
In the arguments, I am passing: SSN1 SSN2 in the arguments. The output should be
Table1->Table1:SSN1
Table2->Table2:SSN1
Table3->Table3:SSN1
Table5->Table5:SSN1
Table1->Table1:SSN2
Table2->Table2:SSN2
Table5->Table5:SSN2
Instead, I am getting the output of:
Table2->Table2:SSN2
Table3->Table3:SSN1
Table5->Table5:SSN2
Table1->Table1:SSN2
Could anyone let me know what is the mistake I am doing here ?
You are trying to put multiple values into a Map using the same key. For each key, a map can only ever hold one value.
Therefore, only the last value that you add for any given key will be visible in the end.
Generally speaking your code suggests that Strings are not the correct data type for your data and that you should be storing it in a more structured form (such as a Map<String,List<String>>).
As i have observed, key is included in value.. so you can use a simple arraylist fro targeted data.. this may help you
public static void main(String[] args) {
String[] valArr;
String ky;
Map<String, String> hmap = new HashMap<String, String>();
List<String> filtered = new ArrayList<String>();
hmap.put("Table1", "Table1:SSN1,SSN2,SSN3,SSN4,SSN5");
hmap.put("Table2", "Table2:SSN1,SSN4,SSN2,SSN5,SSN8,SSN9,SSN10");
hmap.put("Table3", "Table3:SSN4,SSN1");
hmap.put("Table4", "Table4:SSN5,SSN6,SSN7");
hmap.put("Table5", "Table5:SSN8,SSN1,SSN5,SSN2");
if(args.length > 0) {
for(String ssname: args) {
for (Entry<String, String> entry : hmap.entrySet()) {
if (entry.getValue().contains(ssname)) {
ky = entry.getKey();
valArr = entry.getValue().split(":");
filtered.add(valArr[0]+":"+ssname);
}
}
}
}
for (String iter: filtered){
System.out.println(iter.split(":")[0]+ "->" + iter);
}
}
You need to iterate over the items:
valArr = entry.getValue().substring(entry.getValue().indexOf(":")).split(",");
Here is complete code which produces the output you desire:
public static void main(String[] args) {
String[] valArr;
String ky;
Map<String, String> hmap = new HashMap<String, String>();
Map<String, String> filtered = new HashMap<String, String>();
hmap.put("Table1", "Table1:SSN1,SSN2,SSN3,SSN4,SSN5");
hmap.put("Table2", "Table2:SSN1,SSN4,SSN2,SSN5,SSN8,SSN9,SSN10");
hmap.put("Table3", "Table3:SSN4,SSN1");
hmap.put("Table4", "Table4:SSN5,SSN6,SSN7");
hmap.put("Table5", "Table5:SSN8,SSN1,SSN5,SSN2");
if(args.length > 0) {
for(String ssname: args) {
for (Entry<String, String> entry : hmap.entrySet()) {
if (entry.getValue().contains(ssname)) {
ky = entry.getKey();
valArr = entry.getValue().substring(entry.getValue().indexOf(":")).split(",");
for (String val : valArr) {
if (val.equals(ssname)) {
filtered.put(ky, ky+":"+ssname);
}
}
}
}
}
}
for (String iter: filtered.keySet()){
String key = iter.toString();
String value = filtered.get(key).toString();
System.out.println(key + "->" + value);
}
}

How to extract request parameter into name value collection

I have a request parameter like
usrInfo:fname=firstname&lname=lastname&company=&addressLine1=wewqe&addressLine2=wqewqe&city=qweqwe&country=United+States
I want to extract values for each name.
I have written below method but it is failing when there is no value for its corresponding name pair.
private String getRequestParamavalue(SlingHttpServletRequest request, String requestParameter, String requestParamName) {
String reqParamValue = null;
if (StringUtils.isNotBlank(request.getParameter(requestParameter))) {
String[] reqParams = request.getParameter(requestParameter).split("&");
Map<String, String> requestParamMap = new HashMap<>();
String value;
for (String param : reqParams) {
String name = param.split("=")[0];
value = StringUtils.isEmpty(param.split("=")[1]) ? "" : param.split("=")[1];
requestParamMap.put(name, value);
}
reqParamValue = requestParamMap.get(requestParamName);
}
return reqParamValue;
}
Please, give me an advice on this. Thanks.
#Kali Try this
for (String param : reqParams) {
String name = param.split("=")[0];
value = param.split("=").length == 1 ? "" : param.split("=")[1];
requestParamMap.put(name, value);
}
Why not simply do request.getParameter(requestParamName), the HTTPServlet Parent class does the parsing for you.

Adding two values to a key in a HashMap in Java

I am using a file that consists of:
"word","wordtype","definition"
"Base","n.","The lower part of a robe or petticoat."
"Base","n.","An apron."
The output is as follows:
key: "base" value: ["word""wordtype""definition", "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]
key: "word" value: ["word""wordtype""definition", "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]
Desired outcome:
key: "base" value: [ "Base""n.""The lower part of a robe or petticoat.", "Base""n.""An apron."]
key: "word" value: ["word""wordtype""definition"]
Can someone point me in the right direction?
BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(file)));
String line = null;
TreeMap<String, List<String>> def = new TreeMap<String, List<String>>();
List<String> values = new ArrayList<String>();
try {
while ((line = br.readLine()) != null) {
String []parts =line.split(",");
String key = null;
for (int i = 0; i < parts.length; i++){
key = parts[0];
}
values.add(parts[0] + parts[1] + parts[2]);
def.put(key.toLowerCase(), values);
}
A Map cannot work as you request. Any key can only be mapped to a single value.
If you want something akin to what you're doing, but where you can have multiple values for a given key, you could do something like:
List<Map.Entry<String, List<String>>> def = new ArrayList<>();
Map.Entry<String, List<String>> entry = new AbstractMap.SimpleEntry<>(key, list);
def.add(entry);
Then iterate through your def:
for (Map.Entry<String, List<String>> entry : def) {
System.out.println(String.format("Key: %s. Values: %s",
entry.getKey(),
Arrays.toString(entry.getValue().toArray())));
}
Edit:
For your comment: If you want that, you can always roll your own type to store in the Map (or List if you still need duplicate keys):
class WordDescription {
final String wordType;
final String definition;
WordDescription(String wordType, String definition) {
this.wordType = wordType;
definition = definition;
}
String getWordType() {
return wordType;
}
String getDefinition() {
return definition;
}
}
And use that in a List<Map.Entry<String, WordDescription>>. You can make wordType an enum if there's a pre-defined set of them (adjective, noun, etc.).

Get request parameter map in Customiz map?

I want my request parameter map in my custom map like
Map<String, String> reqMap =(HashMap<String, String>)request.getParameterMap();
Above statement gives me following exception
java.lang.ClassCastException: java.util.Collections$UnmodifiableMap
Can any one guide me how can I get all request parameters in my custom map?
Don't want to write for loop to get parameters one by one which cause me performance issue.
Beware of casting the Map to String, String as request.getParameterMap() returns a Map of type String, String[] since Java 6.
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()
Map<String, String> reqMap = request.getParameterMap();
CustomMap<String, String> customMap = new CustomMap<String,String>();
customMap.putAll(reqMap);
Of course, you may need to iterate through the map elements in your putAll() implementation. Otherwise it is not possible.
UPDATE:
Just saw your comment, Thai is easy then,
Map<String, String> reqMap = request.getParameterMap();
Map<String, String> newMap= new HashMap<String,String>();
newMap.putAll(reqMap);
or, you can even pass the reqMap as a constructor argument to new HashMap<String, String>(reqMap);
You can try this method:
public LinkedHashMap<String, String> returnMapOfRequest(HttpServletRequest request)
{
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
try
{
Enumeration<String> parameterNames = request.getParameterNames();
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
Enumeration<String> headers = request.getHeaders(headerName);
while(headers.hasMoreElements())
{
String headerValue = headers.nextElement();
map.put(headerName, headerValue);
}
}
HttpSession session = request.getSession();
Enumeration e = session.getAttributeNames();
while(e.hasMoreElements())
{
String key = (String) e.nextElement();
map.put(key, session.getAttribute(key));
}
while(parameterNames.hasMoreElements())
{
String paramName = parameterNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
for(int i = 0; i < paramValues.length; i++)
{
String paramValue = paramValues[i];
map.put(paramName, paramValue);
}
}
}
catch(Exception e)
{
logger.error("Exception in returnMapOfRequest :: ", e);
}
return map;
}
Change:
Map<String, String> reqMap =(HashMap<String, String>)request.getParameterMap();
To:
Map<String, String> reqMap =(Map<String, String>)request.getParameterMap();

Categories

Resources