I have a string like this but very big string
String data = "created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z,city:Bangalore,Country:Ind";
Now : indicates key-value pairs while , separates the pairs. I want to add the key-value pairs to a HashMap. I am expecting output:-
{created=2022-03-16T07:10:26.135Z,timestamp=2022-03-16T07:10:26.087Z,city=Bangalore,Country=Ind}
I tried in multiple way but I am getting like that
{timestamp=2022-03-16T07, created=2022-03-16T07}
Based on the information provided, here one way to do it. It required both splitting in sections and limiting the size and location of the split.
String data = "created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z,city:Bangalore,Country:Ind";
Map<String, String> map =
Arrays.stream(data.split(","))
.map(str -> str.split(":", 2))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
map.entrySet().forEach(System.out::println);
See this code run live at IdeOne.com.
city=Bangalore
created=2022-03-16T07:10:26.135Z
Country=Ind
timestamp=2022-03-16T07:10:26.087Z
As I said in the comments, you can't use a single map because of the duplicate keys. You may want to consider a class as follows to hold the information
class CityData {
private String created; // or a ZonedDateTime instance
private String timeStamp;// or a ZonedDateTime instance
private String city;
private String country;
#Getters and #setters
}
You could then group all the cities for of a given country for which you had data in a map as follows:
Map<String, List<CityData>> where the Key is the country.
var data="created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z";
var split = data.split(","); // splitting created and timestamp
var created = split[0].substring(8); // 8 is size of 'created:'
var timestamp = split[1].substring(10); // 10 is size of 'timestamp:'
Map<String, String> result = new HashMap<>();
result.put("created", created);
result.put("timestamp", timestamp);
output:
{created=2022-03-16T07:10:26.135Z, timestamp=2022-03-16T07:10:26.087Z}
You need to split the data and iterate on this, split it one more time on colon by specifying index=2 and store the result in a Map. If you want to preserve the order use LinkedHashMap.
Map<String, String> map = new LinkedHashMap<>();
String data = "created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z,city:Bangalore,Country:Ind";
String[] split = data.split(",");
for (String str: split) {
String[] pair = str.split(":", 2);
map.put(pair[0],pair[1]);
}
System.out.println(map);
Output: {created=2022-03-16T07:10:26.135Z, timestamp=2022-03-16T07:10:26.087Z, city=Bangalore, Country=Ind}
Related
I have been trying to get all the values from a string and put them in a map in the following manner:
So I have a string which is like this:
String cookies = "i=lol;haha=noice;df3=ddtb;"
So far I have been trying this out:
final Map<String, String> map = new HashMap<>();
map.put(cookies.split(";")[0].split("=")[0], cookies.split(";")[0].split("=")[1]);
But this way I can only put one value in and it is quite long and ugly. Is there any was to due this with regex or a loop?
You could use a loop to iterate over the key value pairs and put them into the map:
String[] cookieArr = cookies.split(";");
for(String cookieString : cookieArr){
String[] pair = cookieString.split("=");
if(pair.length < 2){
continue;
}
map.put(pair[0], pair[1]);
}
The if is only there to prevent ArrayIndexOutOfBounds expcetions if cookie string is malformed
an alternativ would be using a stream:
Arrays.stream(cookies.split(";")).forEach(cookieStr -> map.put(cookieStr.split("=")[0], cookieStr.split("=")[1]));
As mentioned by #WJS in the comment, you could use map.putIfAbsent(key, vlaue) instead of map.put(key, value) to prevent overriding of values. But in case of cookies it could be a desired behavior to overwrite the old value with the new.
You could do it like this. It presumes your format is consistent.
first splits each k/v pair on ";"
the splits on "=" into key and value.
and adds to map.
if duplicate keys show up, the first one encountered takes precedence (if you want the latest value for a duplicate key then use (a, b)-> b as the merge lambda.)
String cookies = "i=lol;haha=noice;df3=ddtb";
Map<String, String> map = Arrays.stream(cookies.split(";"))
.map(str -> str.split("=")).collect(Collectors
.toMap(a -> a[0], a->a[1], (a, b) -> a));
map.entrySet().forEach(System.out::println);
Prints
df3=ddtb
haha=noice
i=lol
How do I create HashMap of String and List of String out of Set of String with Stream?
Set<String> mySet;
Map<String, List<String>> = mySet.stream().map(string -> {
// string will be my key
// I have here codes that return List<String>
// what to return here?
}).collect(Collectors.toMap(.....)); // what codes needed here?
Thank you.
You don't need the map() step. The logic that produces a List<String> from a String should be passed to Collectors.toMap():
Map<String, List<String>> map =
mySet.stream()
.collect(Collectors.toMap(Function.identity(),
string -> {
// put logic that returns List<String> here
}));
The map operation is useless here, because you don't want to change the string itself, or you would have to map it to an Entry<String, List<String>> and then collect them, but this is not easier.
Instead just build the map, the string as key and get your codes as values :
Map<String, List<String>> map =
mySet.stream().collect(Collectors.toMap(str->str, str-> getCodesFromStr(str));
If you want to know, how it would be with a map operation and use Entry (a pair) :
Map<String, List<String>> = mySet.stream().map(str->
new AbstractMap.SimpleEntry<String,List<String>>(str, getCodesFromStr(str))
).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
I love Guava, and I'll continue to use Guava a lot. But, where it makes sense, I try to use the "new stuff" in Java 8 instead.
"Problem"
Lets say I want to join url attributes in a String. In Guava I would do it like this:
Map<String, String> attributes = new HashMap<>();
attributes.put("a", "1");
attributes.put("b", "2");
attributes.put("c", "3");
// Guava way
String result = Joiner.on("&").withKeyValueSeparator("=").join(attributes);
Where the result is a=1&b=2&c=3.
Question
What is the most elegant way to do this in Java 8 (without any 3rd party libraries)?
You can grab the stream of the map's entry set, then map each entry to the string representation you want, joining them in a single string using Collectors.joining(CharSequence delimiter).
import static java.util.stream.Collectors.joining;
String s = attributes.entrySet()
.stream()
.map(e -> e.getKey()+"="+e.getValue())
.collect(joining("&"));
But since the entry's toString() already output its content in the format key=value, you can call its toString method directly:
String s = attributes.entrySet()
.stream()
.map(Object::toString)
.collect(joining("&"));
public static void main(String[] args) {
HashMap<String,Integer> newPhoneBook = new HashMap(){{
putIfAbsent("Arpan",80186787);
putIfAbsent("Sanjay",80186788);
putIfAbsent("Kiran",80186789);
putIfAbsent("Pranjay",80186790);
putIfAbsent("Jaiparkash",80186791);
putIfAbsent("Maya",80186792);
putIfAbsent("Rythem",80186793);
putIfAbsent("Preeti",80186794);
}};
/**Compining Key and Value pairs and then separate each pair by some delimiter and the add prefix and Suffix*/
String keyValueCombinedString = newPhoneBook.entrySet().stream().
map(entrySet -> entrySet.getKey() + ":"+ entrySet.getValue()).
collect(Collectors.joining("," , "[","]"));
System.out.println(keyValueCombinedString);
/**
* OUTPUT : [Kiran:80186789,Arpan:80186787,Pranjay:80186790,Jaiparkash:80186791,Maya:80186792,Sanjay:80186788,Preeti:80186794,Rythem:80186793]
*
* */
String keyValueCombinedString1 = newPhoneBook.entrySet().stream().
map(Objects::toString).
collect(Collectors.joining("," , "[","]"));
System.out.println(keyValueCombinedString1);
/**
* Objects::toString method concate key and value pairs by =
* OUTPUT : [Kiran=80186789,Arpan=80186787,Pranjay=80186790,Jaiparkash=80186791,Maya=80186792,Sanjay=80186788,Preeti=80186794,Rythem=80186793]
* */
}
> Blockquote
String input data is
{phone=333-333-3333, pr_specialist_email=null, sic_code=2391, status=ACTIVE, address1=E.BALL Drive, fax=333-888-3315, naics_code=325220, client_id=862222, bus_name=ENTERPRISES, address2=null, contact=BYRON BUEGE}
Key and values will increase in the array.
I want to get the value for each key ie myString.get("phone") should return 333-333-3333
I am using Java 1.7, is there any tools I can use this to parse the data and get the values.
Some of my input is having values like,
{phone=000000002,Desc="Light PROPERTITES, LCC", Address1="C/O ABC RICHARD",Address2="6508 THOUSAND OAKS BLVD.,",Adress3="SUITE 1120",city=MEMPHIS,state=TN,name=,dob=,DNE=,}
Comma separator doesn't work here
Here is a simple function that will do exacly what you want. It takes your string as an input and returns a Hashmap containing all the keys and values.
private HashMap<String, String> getKeyValueMap(String str) {
// Trim the curly ({}) brackets
str = str.trim().substring(1, str.length() - 1);
// Split all the key-values tuples
String[] split = str.split(",");
String[] keyValue;
HashMap<String, String> map = new HashMap<String, String>();
for (String tuple : split) {
// Seperate the key from the value and put them in the HashMap
keyValue = tuple.split("=");
map.put(keyValue[0].trim(), keyValue[1].trim());
}
// Return the HashMap with all the key-value combinations
return map;
}
Note: This will not work if there's ever a '=' or ',' character in any of the key names or values.
To get any value, all you have to do is:
HashMap<String, String> map = getKeyValueMap(...);
String value = map.get(key);
You can write a simple parser yourself. I'll exclude error checking in this code for brevity.
You should first remove the { and } characters, then split by ', ' and split each resulting string by =. At last add the results into a map.
String input = ...;
Map<String, String> map = new HashMap<>();
input = input.substring(1, input.length() - 1);
String elements[] = input.split(", ");
for(String elem : elements)
{
String values[] = elem.split("=");
map.put(values[0].trim(), values[1].trim());
}
Then, to retrieve a value, just do
String value = map.get("YOURKEY");
You can use "Google Core Libraries for Java API" MapSplitter to do your job.
First remove the curly braces using substring method and use the below code to do your job.
Map<String, String> splitKeyValues = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator("=")
.split(stringToSplit);
I need to split a sentence into two strings, the first string store as key and the second string store as value in HashMap.
For example:
String sent="4562=This is example";
This is my sentence, I split into two strings using the following line:
sent.split("=");
I want to store the first string (4562) as key, and the second string store as value in HashMap.
Can you please share your ideas or solution for problem?
You are stating your own answer:
HashMap<String, String> map = new HashMap<String, String>(); //initialize the hashmap
String s = "4562=This is example"; //initialize your string
String[] parts = s.split("="); //split it on the =
map.put(parts[0], parts[1]); //put it in the map as key, value
You can store in a hashmap like this:
String sent = "4562=This is example";
String[] split = sent.split("=");
HashMap<Integer, String> keysValues = new HashMap<Integer, String>();
keysValues.put(Integer.parseInt(split[0]), split[1]);
You can store Integer as key and String as value...or String, String either way will work depends on what you want.
the method split returns a String Array so store the result into an String array and call the hashmap.put(key,value) method
like this
String[] a = split.("=");
hasmap.put(a[0],a[1]);
note if you have several = in the string you will loose some of it in the value of the hashmap!
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>();
String s = "4562=This is example";
String[] parts = s.split("=");
if (parts.length == 2) {
myMap.put(parts[0], parts[1]);
}
System.out.println(myMap);
}
Output
{4562=This is example}
enter code here