Android hashMapValues how to get value and format it - java

How can I print the value of my HashMap like this:
String hashMapValues = PHOTO_IDS.get(all values);
hashMapValues output as :
id1, id2, id3, id4, id5
HashMap<String,String> PHOTO_IDS;
onCreate....
PHOTO_IDS = new HashMap<String, String>();
if(vc.readLAST_TAKEN_PIC().equals("imageCam1")) { PHOTO_IDS.put("imageCam1", id); }
else if(vc.readLAST_TAKEN_PIC().equals("imageCam2")) { PHOTO_IDS.put("imageCam2", id); }
else if(vc.readLAST_TAKEN_PIC().equals("imageCam3")) { PHOTO_IDS.put("imageCam3", id); }
else if(vc.readLAST_TAKEN_PIC().equals("imageCam4")) { PHOTO_IDS.put("imageCam4", id); }
else if(vc.readLAST_TAKEN_PIC().equals("imageCam5")) { PHOTO_IDS.put("imageCam5", id); }
many many thanks for help.
UPDATED_____________________________________________
Thank you all for your reply. here is the working code:
String hashmapValues = PHOTO_IDS.values().toString();
TMP_PHOTO_ID = hashmapValues.replaceAll("[\\[\\]]", "");

You can use Map.getValues() for this purpose.
like
System.out.println(PHOTO_IDS .values());
Output will be like
[id1, id2, id3, id4, id5]
Here you need to relace [ and ] characters from string.

You can use entrySet() to print all values like this:
UPDATE : Using StringBuilder
StringBuilder s = new StringBuilder();
for(Entry<String,String> e : PHOTO_IDS.entrySet()){
s.append(e.getValue() + ", ");
}
String result = s.toString();
Refer HashMap#entrySet() java documentation for more information.
There is one more way to get the comma-seperated values directly as below :
String result = PHOTO_IDS.values().toString();
But this will return output as [id1, id2, id3, id4, id5], so you just need to get rid of those brackets[] which you can do easily by using substring

If you don't want the brackets around your value list, you can do the following. But for all solutions if you are concerned about order, you may want to consider using a LinkedHashMap
StringBuilder sb = new StringBuilder();
for(String val : map.values()){
sb.append(val+",");
}
String result = sb.toString();
System.out.println(result.substring(0, result.length() - 1)); //This will remove the last comma.

Related

How to Loop next element in hashmap

I have a set of strings like this
A_2007-04, A_2007-09, A_Agent, A_Daily, A_Execute, A_Exec, B_Action, B_HealthCheck
I want output as:
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
Key = B, Value = [Action,HealthCheck]
I'm using HashMap to do this
pckg:{A,B}
count:total no of strings
reports:set of strings
Logic I used is nested loop:
for (String l : reports[i]) {
for (String r : pckg) {
String[] g = l.split("_");
if (g[0].equalsIgnoreCase(r)) {
report.add(g[1]);
dirFiles.put(g[0], report);
} else {
break;
}
}
}
I'm getting output as
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
How to get second key?
Can someone suggest logic for this?
Assuming that you use Java 8, it can be done using computeIfAbsent to initialize the List of values when it is a new key as next:
List<String> tokens = Arrays.asList(
"A_2007-04", "A_2007-09", "A_Agent", "A_Daily", "A_Execute",
"A_Exec", "P_Action", "P_HealthCheck"
);
Map<String, List<String>> map = new HashMap<>();
for (String token : tokens) {
String[] g = token.split("_");
map.computeIfAbsent(g[0], key -> new ArrayList<>()).add(g[1]);
}
In terms of raw code this should do what I think you are trying to achieve:
// Create a collection of String any way you like, but for testing
// I've simply split a flat string into an array.
String flatString = "A_2007-04,A_2007-09,A_Agent,A_Daily,A_Execute,A_Exec,"
+ "P_Action,P_HealthCheck";
String[] reports = flatString.split(",");
Map<String, List<String>> mapFromReportKeyToValues = new HashMap<>();
for (String report : reports) {
int underscoreIndex = report.indexOf("_");
String key = report.substring(0, underscoreIndex);
String newValue = report.substring(underscoreIndex + 1);
List<String> existingValues = mapFromReportKeyToValues.get(key);
if (existingValues == null) {
// This key hasn't been seen before, so create a new list
// to contain values which belong under this key.
existingValues = new ArrayList<>();
mapFromReportKeyToValues.put(key, existingValues);
}
existingValues.add(newValue);
}
System.out.println("Generated map:\n" + mapFromReportKeyToValues);
Though I recommend tidying it up and organising it into a method or methods as fits your project code.
Doing this with Map<String, ArrayList<String>> will be another good approach I think:
String reports[] = {"A_2007-04", "A_2007-09", "A_Agent", "A_Daily",
"A_Execute", "A_Exec", "P_Action", "P_HealthCheck"};
Map<String, ArrayList<String>> map = new HashMap<>();
for (String rep : reports) {
String s[] = rep.split("_");
String prefix = s[0], suffix = s[1];
ArrayList<String> list = new ArrayList<>();
if (map.containsKey(prefix)) {
list = map.get(prefix);
}
list.add(suffix);
map.put(prefix, list);
}
// Print
for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> valueList = entry.getValue();
System.out.println(key + " " + valueList);
}
for (String l : reports[i]) {
String[] g = l.split("_");
for (String r : pckg) {
if (g[0].equalsIgnoreCase(r)) {
report = dirFiles.get(g[0]);
if(report == null){ report = new ArrayList<String>(); } //create new report
report.add(g[1]);
dirFiles.put(g[0], report);
}
}
}
Removed the else part of the if condition. You are using break there which exits the inner loop and you never get to evaluate the keys beyond first key.
Added checking for existing values. As suggested by Orin2005.
Also I have moved the statement String[] g = l.split("_"); outside inner loop so that it doesn't get executed multiple times.

how to create comma separated string in single quotes from arraylist of string in JAVA

I have requirement in Java to fire a query on MS SQL like
select * from customer
where customer.name in ('abc', 'xyz', ...,'pqr');
But I have this IN clause values in the form of ArrayList of String. For ex: the list look like {"abc","xyz",...,"pqr"}
I created a Prepared Statement :
PreparedStatement pStmt = conn.prepareStatement(select * from customer
where customer.name in (?));
String list= StringUtils.join(namesList, ",");
pStmt.setString(1,list);
rs = pStmt.executeQuery();
But the list is like "abc,xyz,..,pqr", but I want it as "'abc','xyz',..,'pqr'"
so that I can pass it to Prepares Statement.
How to do it in JAva with out GUAVA helper libraries.
Thanks in Advance!!
I know this is a really old post but just in case someone is looking for how you could do this in a Java 8 way:
private String join(List<String> namesList) {
return String.join(",", namesList
.stream()
.map(name -> ("'" + name + "'"))
.collect(Collectors.toList()));
}
List<String> nameList = ...
String result = nameList.stream().collect(Collectors.joining("','", "'", "'"));
For converting the string you can try this:
String list= StringUtils.join(namesList, "','");
list = "'" + list + "'";
But i dont thing it's a good idea to pass one string for multiple params.
Even if you formatted the String as you wish, it won't work. You can't replace one placeholder in the PreparedStatement with multiple values.
You should build the PreparedStatement dynamically to have as many placeholders as there are elements in your input list.
I'd do something like this :
StringBuilder scmd = new StringBuilder ();
scmd.append ("select * from customer where customer.name in ( ");
for (int i = 0; i < namesList.size(); i++) {
if (i > 0)
scmd.append (',');
scmd.append ('?');
}
scmd.append (")");
PreparedStatement stmt = connection.prepareStatement(scmd.toString());
if (namesList.size() > 0) {
for (int i = 0; i < namesList.size(); i++) {
stmt.setString (i + 1, namesList.get(i));
}
}
rs = stmt.executeQuery();
You can use a simple separator for this type of activity. Essentially you want an object that evaluates to "" the first time around but changes after the first request to return a defined string.
public class SimpleSeparator<T> {
private final String sepString;
boolean first = true;
public SimpleSeparator(final String sep) {
this.sepString = sep;
}
public String sep() {
// Return empty string first and then the separator on every subsequent invocation.
if (first) {
first = false;
return "";
}
return sepString;
}
public static void main(String[] args) {
SimpleSeparator sep = new SimpleSeparator("','");
System.out.print("[");
for ( int i = 0; i < 10; i++ ) {
System.out.print(sep.sep()+i);
}
System.out.print("]");
}
}
I did it as following with stream. Almost the same, but a bit shorter.
nameList = List.of("aaa", "bbb", "ccc")
.stream()
.map(name -> "'" + name + "'")
.collect(Collectors.joining(","));
I guess the simplest way to do it is using expression language like that:
String[] strings = {"a", "b", "c"};
String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "\'").replace(", ", "\',\'" );

How to get original codes from generated pattern in java?

Suppose I have java.util.Set<String> of "200Y2Z", "20012Y", "200829", "200T2K" which follows the same pattern "200$2$", where "$" is the placeholder. Now which is the most efficient way to get Set of just unique codes from such strings in Java?
Input: java.util.Set<String> of "200Y2Z", "20012Y", "200829", "200T2K"
Expected output: java.util.Set<String> of "YZ", "1Y", "89", "TK"
My Try ::
public static void getOutPut()
{
Set<String> input = new HashSet<String>();
Set<String> output = new HashSet<String>();
StringBuffer out = null;
for(String in : input)
{
out = new StringBuffer();
StringCharacterIterator sci = new StringCharacterIterator(in);
while (sci.current( ) != StringCharacterIterator.DONE){
if (sci.current( ) == '$')
{
out.append(in.charAt(sci.getIndex()));
}
sci.next( );
}
output.add(out.toString());
}
System.out.println(output);
}
It is working fine, but is there any efficient way than this to achieve it? I need to do it for more than 1000K codes.
Get the indexes of the placeholder in the pattern:
int i = pattern.getIndexOf('$');
You'll must to iterate to obtain all the indexes:
pattern.getIndexOf('$', lastIndex+1);
The loop and the checks are up to you.
Then use charAt with the indexes over each element of the set.

Get parameter after "#" from url java

I have a redirect uri of the form https://stackexchange.com/oauth/login_success#access_token=token&expires=5678. I am trying to get the acces token from this url. tried following methods
uri.getQueryParameter("access_token"); //will return null since it is not a query param
uri.getFragment(); //will return "access_token=token&expires=5678" so i need to seperate it again.
Any direct methods? Pls help
Some one might find this helpful
String queryAfterFragment = uri.getFragment();
String dummy_url = "http://localhost?" + queryAfterFragment;
Uri dummy_uri = Uri.parse(dummy_url);
String access_token = dummy_uri.getQueryParameter("access_token");
Works like a charm and easy to use, thank me later :-)
Simple and elegant solution which can get the values which you want:
public static Map<String, String> parseUrlFragment (String url) {
Map<String, String> output = new LinkedHashMap<> ();
String[] keys = url.split ("&");
for (String key : keys) {
String[] values = key.split ("=");
output.put (values[0], (values.length > 1 ? values[1] : ""));
}
return output;
}
It's using LinkedHashMap to represent values, so it's output:
Map<String, String> data = parseUrlFragment (uri.getFragment ());
data.get ("access_token") // token
data.get ("expires") // 5678
You can try in this way
String str = "https://stackexchange.com/oauth/
login_success#access_token=token&expires=5678";
int indexOfHash = str.indexOf("#");
// now you can substring from this
String subStr = str.substring(indexOfHash+1, str.length());
System.out.println(subStr);
// now you can substring from &
String sStr=subStr.substring(0,subStr.indexOf("&"));
System.out.println(sStr);
// now you can get token
String[] arr=sStr.split("=");
System.out.println(arr[0]);
System.out.println(arr[1]);
Out put
access_token=token&expires=5678
access_token=token
access_token
token
You could use the String method split(String) with Regex
str.split("#|&|=")
this splits the string by the passed 3 chars and you get an array with all the splitted parts.
String s =
"https://stackexchange.com/oauth/login_success#access_token=token&expires=5678";
final String[] split = s.split("#|&|=");
for (String s1 : split) {
System.out.println(s1);
}
Output:
https://stackexchange.com/oauth/login_success
access_token
token
expires
5678

How to sort a string into a map and print the results

I have a string in the format nm=Alan&hei=72&hair=brown
I would like to split this information up, add a conversion to the first value and print the results in the format
nm Name Alan
hei Height 72
hair Hair Color brown
I've looked at various methods using the split function and hashmaps but have had no luck piecing it all together.
Any advice would be very useful to me.
Map<String, String> aliases = new HashMap<String, String>();
aliases.put("nm", "Name");
aliases.put("hei", "Height");
aliases.put("hair", "Hair Color");
String[] params = str.split("&"); // gives you string array: nm=Alan, hei=72, hair=brown
for (String p : params) {
String[] nv = p.split("=");
String name = nv[0];
String value = nv[1];
System.out.println(nv[0] + " " + aliases.get(nv[0]) + " " + nv[1]);
}
I really do not understand what you problem was...
Try something like this:
static final String DELIMETER = "&"
Map<String,String> map = ...
map.put("nm","Name");
map.put("hei","Height");
map.put("hair","Hair color");
StringBuilder builder = new StringBuilder();
String input = "nm=Alan&hei=72&hair=brown"
String[] splitted = input.split(DELIMETER);
for(Stirng str : splitted){
int index = str.indexOf("=");
String key = str.substring(0,index);
builder.append(key);
builder.append(map.get(key));
builder.append(str.substring(index));
builder.append("\n");
}
A HashMap consists of many key, value pairs. So when you use split, devise an appropriate regex (&). Once you have your string array, you can use one of the elements as the key (think about which element will make the best key). However, you may now be wondering- "how do I place the rest of elements as the values?". Perhaps you can create a new class which stores the rest of the elements and use objects of this class as values for the hashmap.
Then printing becomes easy- merely search for the value of the corresponding key. This value will be an object; use the appropriate method on this object to retrieve the elements and you should be able to print everything.
Also, remember to handle exceptions in your code. e.g. check for nulls, etc.
Another thing: your qn mentions the word "sort". I don't fully get what that means in this context...
Map<String, String> propsMap = new HashMap<String, String>();
Map<String, String> propAlias = new HashMap<String, String>();
propAlias.put("nm", "Name");
propAlias.put("hei", "Height");
propAlias.put("hair", "Hair Color");
String[] props = input.split("&");
if (props != null && props.length > 0) {
for (String prop : props) {
String[] propVal = prop.split("=");
if (propVal != null && propVal.length == 2) {
propsMap.put(propVal[0], propVal[1]);
}
}
}
for (Map.Entry tuple : propsMap.getEntrySet()) {
if (propAlias.containsKey(tuple.getKey())) {
System.out.println(tuple.getKey() + " " + propAlias.get(tuple.getKey()) + " " + tuple.getValue());
}
}

Categories