I have a String that has been constructed from another LinkedHashMap using toString method, and I want to do the reverse in creating another LinkedHashMap<String, String> with this String representation of the previous LinkedHashMap.
Is it possible withing using String splits and manually doing it in a loop calling LinkedHashMap.put() ?
I think this could work?
LinkedHashMap params = new LinkedHashMap();
String[] split = paramsString2.split(",");
for (int i = 0; i < split.length; i++) {
String[] nameValue = split[i].split("=");
params.put(nameValue[0], nameValue[1]);
}
return params;
Assume the string is of the form
key1=value1;key2=value2;key3=value3
Yes, it is possible. Use string.split(";") to separate the map entries into an array.
Then loop through the array, and for each entry, use string.split("=") to separate the key from the value.
Then add the key and value to the new LinkedHashMap:
String[] parts = entry.split("=");
map.put(parts[0], parts[1]); //parts[0] is the key, parts[1] is the value
Sure it is possible, but why should you do such horrible stuff?
Anyway, yes it is possible, you could also use the guava library to accomplish such a job.
guava-library
Related
I am very new to java had a question regarding returning the dictionary with the help of hashmap. The problem is I have string array let say with four names and I have to iterate and differentiate name according to the string length and if the key does not match I have to create other list and if it matches I have to simply append the string.
Basically the expected output should be like this
3:kel
4:john,aron
5:sonny
6:abraham
I tried little bit but stuck code looks like this
public static void main(String arg[])
{
HashMap<integer, ArrayList<String>> map = new HashMap<integer, ArrayList<String>>();
ArrayList<String> namelist = new ArrayList<String>();
obj.add("john");
obj.add("kel");
obj.add("abraham");
obj.add("sonny");
obj.add("aron");
map.put(3, namelist);
for (int i = 0; i < namelist.size(); i++) {
String element = namelist[i];
String nextElement = elements[i+1];
}
}
Your datatypes on the HashMap are not ideal. You want HasMap<Integer, List<String>>, although you could use String as a key if you call toString on the integer length of the name before using it as a key. Then, loop through the obj list and check if the length of the string you're on (obj[i].length()) exists in map using map.containsKey(obj[i].length()). If it does exist, you will map.get(obj[i].length()).add(obj[i]), and if it doesn't you will create a new ArrayList containing obj[i] and use the .put method on the HashMap to add it.
In the code you posted, first appears to not be defined.
I would rename obj to nameList, or something more descriptive. It's not an object.
Java 8's streaming capabilities offer a pretty elegant one-liner for this with the built in groupingBy collector:
Map<Integer, List<String>> map =
obj.stream().collect(Collectors.groupingBy(String::length));
I need to create a list with values of type - (long,String)
like -
ArrayList a = new ArrayList();
a.add(1L,branchName);
How can I do this because if I use list It will accept only int,String.
You should note that ArrayList's add(int,String) adds the String element in the given int index (if the index is valid). The int parameter is not part of the contents of the ArrayList.
Perhaps an ArrayList is not the correct choice for you. If you wish to map Long keys to String values, use Map<Long,String>.
Map<Long,String> a = new HashMap<> ();
a.put(1L,branchName);
You can define a custom class, e.g.
class IndexAndBranchName {
long index;
String branchName;
}
and then add instances of this to the ArrayList:
ArrayList<IndexAndBranchName> a = new ArrayList<>();
a.add(new IndexAndBranchName(index, branchName));
Whether you use this approach or something like Eran's depends upon what you need to use the list for subsequently:
If you want to look "branches" up by index, use a Map; however, you can only store a single value per key; you could use a Guava Multimap or similar if you want multiple values per key.
If you simply want all of the index/branch name pairs, you can use this approach.
You can use the below code for your question.
HashMap is also a better option , but if you want only ArrayList then use it.
List<Map<Object, Object>> mylist = new ArrayList<Map<Object, Object>>();
Map map = new HashMap<>();
map.put(1L, "BranchName");
mylist.add(map);
In my class Feeds I have along with other members a member variable called "Date" which is of String type. I have an ArrayList of Feeds objects. I want to find the occurrences of objects which have the same date String. The occurrences can then be put in a HashMap that contains the String Date as key and # of occurrences as value.
Something along these lines:
List<Feeds> m_feeds = new ArrayList<Feeds>();
//add all feeds objects
m_feeds.add(...);
int occurrences = 0;
HashMap<String, Integer> repeatedDatabase = new HashMap<String, Integer>();
for (Feeds f : m_feeds){
occurrences = Collections.frequency(m_feeds, f.date);
// i know this method compares objects but i want to know how
// only a single variable can be done
repeatedDatabase.put(f.date, occurrences);
}
Other than giving you a simple solution, I took the liberty of fixing some things in your code please take a look:
List<Feeds> mFeeds = new ArrayList<>(); //If you are using Java 7+ you do not need to declare explicitly the Type in Diamonds. If you aren't, ignore this. Also fixed name to adapt to Java standards.
//add all feeds objects
m_feeds.add(...);
HashMap<String, Integer> repeatedDatabase = new HashMap<>(); //See Above.
for (Feeds f : m_feeds){
String s = f.date; //Suggestion: use a getter method, do not make public variables accessible outside class
Integer i = repeatedDatabase.get(s);
if (i == null){
repeatedDatabase.put(s, 1);
} else {
repeatedDatabase.put(s, i+1);
}
}
Your code will work if you properly overrode equals and in the Feeds class to return true for two Feeds instances having the same date (since if you try to put the same key in the Map twice, the new value will override the old value, and since in your case the values would also be the same, it would make no difference). However, each call to Collections.frequency would iterate over the entire List, which would give you an O(n^2) time complexity.
One way to make it more efficient :
for (Feeds f : m_feeds){
if (!repeatedDatabase.containsKey(f.date)) {
occurrences = Collections.frequency(m_feeds, f.date);
repeatedDatabase.put(f.date, occurrences);
}
}
This would still do more iterations than necessary. It would call Collections.frequency once for each unique date, which means you would iterate the List as many times as there are unique dates.
A more efficient implementation will not use Collection.frequency at all. Instead, you'll iterate just one time over the list and count the number of occurrences of each date yourself. This would give you an O(n) time complexity.
for (Feeds f : m_feeds){
if (!repeatedDatabase.containsKey(f.date)) {
repeatedDatabase.put(f.date, 1);
} else {
repeatedDatabase.put(f.date, repeatedDatabase.get(f.date)+1);
}
}
Why don't use directly the hashMap?
you can do something like
HashMap<String,Iteger> map = new HashMap<>();
for (Feeds f : m_feeds){
if (map.contains(f.getDate()) { // use the method to get the date
map.put(f.getDate(),map.get(f)+1);
else
map.put(f.getDate(),1);
}
I didn't test the code but it should work.
A small update to Angelo's answer..pushing it a bit further.. you can also use a map of string,int[] like this
Map<String,int[]> map = new HashMap<>();
int[] countArray = map.get(key);
if(countArray == null)
map.put(key, new int[]{0});
else
countArray[0]++;
Using the beauty of references :)
For example: String[] str = {"M1","M1","M1","M2","M3"};
The most recommended is the answer - HashSet. Which methods or you have better idea?
Unless you want to implement this yourself, a Set is the way to go. A set will only allow unique elements to be added and will automatically filter duplicates.
The HashSet functionality works as follows:
The hash is computed for the object. Next the set checks if any of the objects with the same hash-value .equals() the new value. If so, the new value is ignored. If not, it is added to the set.
If you add everything to the set and then ask for its size, you will get the amount of unique elements.
new HashSet(Arrays.asList(str)).size();
I prefer to use things that are already provided natively. Which in your requirement is Set.
You can do the following -
Set<String> set = new HashSet<String>(Arrays.asList(str));
set.size();
You can try this too
String[] str = {"M1","M1","M1","M2","M3"};
HashMap<String,String> map=new HashMap<>();
for(String i:str){
map.put(i, i);
}
System.out.println(map.keySet().size());
Instead of creating a temporary list as in other answers, you can also use:
Set<String> set = new HashSet<> ();
Collections.addAll(set, str);
int countUnique = set.size();
I have a HashMap. The key will be a string and value can be anything ranging from a variable to a ArrayList.
The problem is I have an ArrayList. The values stored in the ArrayList are Region1,Region2,Region3,Region4.
So when I put this ArrayList in HashMap and print the HashMap I get the output as
[Region1,Region2,Region3,Region4].
Problem is I need to insert this whole comma separated String in Db and my procedure cannot recognize [] in this output.
How can I solve it..I cannot change anything at DB end.
Here's the code snippet:-
ArrayList<String> Region=new ArrayList<String>();
Region.add("Region1");
Region.add("Region2");
Region.add("Region3");
System.out.println(Region);
Output is [Region1, Region2, Region3]
I put this ArrayList in HashMap
HashMap<String,Object> regionHashMap=new HashMap<String,Object>();
regionHashMap.put("regionssss", Region);
System.out.println(regionHashMap);
Output is {regionssss=[Region1, Region2, Region3]}.
How can i Remove [] from the ArrayList...
I already succedded by using StringBuffer and Iterator but I cannot use it everytime Since I have huge number of ArrayList which will go inside the HashMap..
The String representation of a List automatically encloses with "[ ]" characters.
You could either create your own 'toString' method:
private String listToString(List<?> l) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < l.size(); i++) {
sb.append(l.get(i));
if (i != l.size() -1) sb.append(", ");
}
return sb.toString();
}
Or, you could use the substring function to remove the braces:
String s = list.toString();
s = s.substring(1, s.length()-1);
Don't use toString() at all. It is not meant to be used to create formatted UI strings. It is a developer tool, not a user presentation tool.
To do what you want is to just create a method to do your display and do the formatting in that method instead.
see this post to get more on this.
Try subclassing HashMap and override the toString() method