Java custom implode methode like in PHP - java

I am trying to replicate the php function implode() in Java.
This is what I made:
private String implode(String delimiter, Map<String, String> map){
StringBuilder sb = new StringBuilder();
for(Entry<String, String> e : map.entrySet()){
sb.append(" "+delimiter+" ");
sb.append(" " + e.getKey() + " = '" + e.getValue() + "' ");
}
return sb.toString();
}
Testing:
Map<String, String> myList = new HashMap<String, String>();
myList.put("address", "something1");
myList.put("last_name", "something2");
myList.put("first_name", "something3");
update_database("dummy", myList, "");
public void update_database(String table, Map<String, String> update_list, String condition){
String query = "UPDATE " + table + " SET ";
query += implode(",", update_list) + " " + condition;
System.out.println(query);
}
Output:
UPDATE dummy SET , address = 'something' , last_name = 'something2',
first_name = 'something3'
If you worked with mysql before, you know that it's not a valid query because the string query start with ",".
How can I format my string to get a correct query?

You could try something like this:
Own Implementation
private String implode(String delimiter, Map<String, String> map){
boolean first = true;
StringBuilder sb = new StringBuilder();
for(Entry<String, String> e : map.entrySet()){
if (!first) sb.append(" "+delimiter+" ");
sb.append(" " + e.getKey() + " = '" + e.getValue() + "' ");
first = false;
}
return sb.toString();
}
StringUtils
Another solution would be to use public static String join(Collection collection, char separator)

You don't need to write this yourself. There's already a library with this functionality named guava made by google. It has a class called a Joiner. Here's an example:
Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");
This returns the string "Harry; Ron; Hermione". Note that all input elements are converted to strings using Object.toString() before being appended.

Related

If I have two keys with equal value, how do I return a Set<String> kinda (value + " - " + key ", " + key)?

This code works only when I have a pair like name(value) + number(key), but I'm stuck with situation like - name + number, number. It returns name + number1, name + number2
public Set<String> getAllContacts() {
TreeSet<String> contacts = new TreeSet<>();
if (phoneBook.isEmpty()) {
return new TreeSet<>();
} else {
for (Map.Entry<String, String> entry : phoneBook.entrySet()) {
contacts.add(entry.getValue() + " - " + entry.getKey());
}
}
return contacts;
}
Basically you want to invert key and value of your phoneBook map. Since one name can have multiple numbers according to your example the output structure should be Map<String, List<String>>. With this name oriented phone book you can easily create your contact collection. E.g.
Map<String, List<String>> phoneBookByName = new HashMap<>();
phoneBook.forEach((k, v) -> {
List<String> numbers = phoneBookByName.computeIfAbsent(k, s -> new ArrayList<>());
numbers.add(v);
});
TreeSet<String> contacts = new TreeSet<>();
phoneBookByName.forEach((k, v) -> contacts.add(k + " - " + String.join(", ", v)));
return contacts;
or using streams
Map<String, List<String>> phoneBookByName = phoneBook.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
return phoneBookByName.entrySet().stream()
.map(entry -> entry.getKey() + " - " + String.join(", ", entry.getValue()))
.collect(Collectors.toCollection(TreeSet::new));

Regex to get particular values from a string data

While executing a particular shell command am getting following output as follows and keeping this in a string variable
dat /var/france.log
exit
bluetooth_mac=45h6kuu
franceIP=testMarmiton
build_type=BFD
france_mac=F4:0E:83:35:E8:D1
seloger_mac=F4:0E:83:35:E8:D0
tdVersion=1.2
td_number=45G67j
france_mac=fjdjjjgj
logo_mac=tiuyiiy
logout
Connection to testMarmiton closed.
Disconnected channel and session
From this i have too fetch particular details like below and put htese values in a Map. How i can perform this using java.
bluetooth_mac=45h6kuu
build_type=BFD
tdVersion=1.2
seloger_mac=F4:0E:83:35:E8:D0
france_mac=fjdjjjgj
Map<String, String> details =new HashMap<String,String>();
details.put(bluetooth_mac, 45h6kuu);
details.put(build_type, BFD)
etc
etc
Solution 1
If you are using Java 8 you can use :
String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, String> result = stream
.filter(line -> line.matches("\\w+=\\w+"))
.map(line -> line.split("="))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
} catch (IOException e) {
e.printStackTrace();
}
Outputs
{franceIP=testMarmiton, bluetooth_mac=45h6kuu, logo_mac=tiuyiiy, td_number=45G67j, france_mac=fjdjjjgj, build_type=BFD}
Solution 2
It seems that you have multiple line which have the same name, in this case I would like to group by a Map<String, List<String>> :
String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, List<String>> result = stream
.filter(line -> line.matches("[^=]+=[^=]+")) // filter only the lines which contain one = signe
.map(line -> line.split("=")) // split with = sign
.collect(Collectors.groupingBy(e -> e[0], Collectors.mapping(e -> e[1], Collectors.toList())));
result.forEach((k, v) -> System.out.println(k + " : " + v));
} catch (IOException e) {
e.printStackTrace();
}
Outputs
franceIP : [testMarmiton]
bluetooth_mac : [45h6kuu]
logo_mac : [tiuyiiy]
td_number : [45G67j]
seloger_mac : [F4:0E:83:35:E8:D0]
france_mac : [F4:0E:83:35:E8:D1, fjdjjjgj]
tdVersion : [1.2]
build_type : [BFD]
public static void main(String[] args) {
String str="abc def \n"
+ "key=123 \n "
+ "pass=456 \n"
+ "not working";
String[] sarray=str.split("\\r?\\n");
for (String eachline : sarray) {
System.out.println("line " + " : " + eachline);
if(eachline.contains("="))
{
String[] sarray2=eachline.split("=");
System.out.println("key:" +sarray2[0] +":Value:"+ sarray2[1]);
}
}
System.out.println(""+sarray.length);
}
Use split("\r?\n") for new line splitting.
You could try:
Pattern re = Pattern.compile("^\\s*(.*)\\s*=(.*)$", Pattern.MULTILINE);
Matcher matcher = re.matcher(input);
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
Here's a complete example, extracting the value using regex-matching and building a HashMap (the appropriate map for key-value pairs). You can copy the whole program and run it yourself:
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class main {
public static void main(String[] args) {
String input = // Your input log
"dat /var/france.log\n" +
"\n" +
"exit\n" +
"\n" +
"root#france24:~# \n" +
"root#france24:~# dat /var/france.log\n" +
"bluetooth_mac=45h6kuu\n" +
"franceIP=testMarmiton\n" +
"build_type=BFD\n" +
"france_mac=F4:0E:83:35:E8:D1\n" +
"seloger_mac=F4:0E:83:35:E8:D0\n" +
"tdVersion=1.2\n" +
"td_number=45G67j\n" +
"france_mac=fjdjjjgj\n" +
"logo_mac=tiuyiiy\n" +
"root#france24:~# \n" +
"root#france24:~# exit\n" +
"logout\n" +
"Connection to testMarmiton closed.\n" +
"\n" +
"Disconnected channel and session";
String[] keys = {
"bluetooth_mac",
"build_type",
"tdVersion",
"seloger_mac",
"france_mac"
};
HashMap<String, String> map = new HashMap<>();
for(String key : keys){
String value = getValueOf(input, key);
if(value != null)
map.put(key, value);
}
for(String key : keys)
System.out.println(key + " = " + map.get(key));
}
public static String getValueOf(String input, String key){ //returns null if not found
String result = null;
Pattern pattern = Pattern.compile(key + "=.*+\\s");
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
result = matcher.group();
result = result.substring(result.indexOf('=') + 1, result.length() - 1);
}
return result;
}
}
Output (add more keys to the key-string if you want get more values):
bluetooth_mac = 45h6kuu
build_type = BFD
tdVersion = 1.2
seloger_mac = F4:0E:83:35:E8:D0
france_mac = F4:0E:83:35:E8:D1

Make Dynamic Query with JdbcTemplate

I have one question regarding make dynamic query with JdbcTemplate.
My code is as below :
String insertQueries = "INSERT INTO " + tablename;
StringJoiner joiner = new StringJoiner(",");
StringJoiner joiner1 = new StringJoiner(",");
StringJoiner joiner2 = new StringJoiner(",");
while (mapIterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
key = joiner.add((String) mapEntry.getKey()).toString();
// value = joiner1.add("\"" + (String) mapEntry.getValue() + "\"").toString();
value = joiner1.add("\"" + (String) mapEntry.getValue() + "\"").toString();
value1 = joiner2.add("?").toString();
}
insertQueries += " (" + key + ")";
insertQueries += " VALUES ("+value1+")" ;
int row = jdbcTemplate.update(insertQueries, value);
Now my question is that I want same number of "value" as per auto generate question marks in insert query.
Right now, the value variable consider as one string so if I have 2 or more question marks then in value variable only one full string with comma separated so it's not working.
See below my query :
INSERT INTO tablename (fname, lname) VALUES ("abc, xyz") ;
And I want as below :
INSERT INTO tablename (fname, lname) VALUES ("abc", "xyz") ;
**StringJoiner joiner2 = new StringJoiner(",", "(", ")");**
while (mapIterator.hasNext()) {
//change in value1 as
value = "\"" + (String) mapEntry.getValue() + "\"";
value1 = joiner2.add(value);
myvalue = joiner2.add("?");
}
//change insertQueries as with value as (? ,?)
insertQueries += " VALUES "+ myvalue+"" ;
//get value1 as ("abc", "xyz")
//update query as
int row = jdbcTemplate.update(insertQueries, value1);

how to convert a hash table in string in java

I'm new in java and i want to convert a hash table in the form of a string, with each pair separated by any special character. I'm little confuse how to apply loop on the hash table and extract values from. Please explain me how to do this. Thanks in advance
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
foreach(){
hashstring += key + "=" + hashtable[key] + "|";
}
return hashstring;
}
You can use Map.Entry as follows:
String hashstring= "";
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
String seperator = "|";
StringBuilder sb = new StringBuilder();
Set<String> keys = detailHashtable.keySet();
for(String key: keys) {
sb.append(key+"="+detailHashtable.get(key)+ seperator);
}
return sb.toString();
Both the HashMap and HashTable can use Map.Entry to get both key and value simultaneously.
String hashstring= "";
for (Map.Entry<String, String> entry : detailHashtable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
Refer the API to know what operations can be used.
http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html#entrySet()
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
for(Entry<String,String> entry : detailHashtable.entrySet()){
hashstring += entry.getKey() + "=" + entry.getValue() + "| ";
}
return hashstring;
}
Map from which Hashtable extends provides the method Map.entrySet(), which returns a set containing all entries in the map.
for(Map.Entry e : detailHashTable.entrySet()){
Object key = e.getKey();
Object value = e.getValue();
...
}
use entry.getKey().to String() and entry.getValue().toString();

Android: Get the entire array the value/key is in ArrayList<HashMap<String, String>>

I am trying to get v8 from the third array inside following arraylist
String[][] test = {
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7", "v8"}
};
ArrayList<String[]> test2= new ArrayList<String[]>(Arrays.asList(test));
Log.e("v1: ", "" + test2.get(0));
for (int j = 0; j <= test2.size(); j++) {
for (String[] arrays: test2) {
for (String string2 : arrays) {
if (string2.equalsIgnoreCase("v8")) {
Log.e("LOOOOOOOOOG", "" + test2.indexOf("v8")); // 3
}else {
Log.e("LOOOOOOOOOG", "Cant find it!!");
}
}
}
}
How would i do this?
I currently just get either -1 or Cant find it!!
I am trying to solve the above problem to solve the following HashMap problem.
public static void updateJSONdata() {
mEmailList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EMAILS_URL);
try {
mEmails = json.getJSONArray("info");
// looping through all emails according to the json object returned
for (int i = 0; i < mEmails.length(); i++) {
JSONObject c = mEmails.getJSONObject(i);
// gets the content of each tag
String email = c.getString(TAG_EMAIL);
String firstName = c.getString(TAG_FNAME);
String lastName = c.getString(TAG_LNAME);
String address = c.getString(TAG_ADDRESS);
String phoneNumber = c.getString(TAG_PHONE);
String city = c.getString(TAG_CITY);
String state = c.getString(TAG_STATE);
String zip = c.getString(TAG_ZIP);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EMAIL, email);
map.put(TAG_FNAME, firstName);
map.put(TAG_LNAME, lastName);
map.put(TAG_ADDRESS, address);
map.put(TAG_PHONE, phoneNumber);
map.put(TAG_CITY, city);
map.put(TAG_STATE, state);
map.put(TAG_ZIP, zip);
// adding HashList to ArrayList
mEmailList.add(map);
for (HashMap<String, String> maps : mEmailList){
for (Entry<String, String> mapEntry : maps.entrySet()){
String key = mapEntry.getKey();
String value = mapEntry.getValue();
if (value.equals(passedEmail)) {
Log.e("Is this email in the database?", value + " Is in the database!!!");
int index = map.get(key).indexOf(value);
Log.e("mEmailList: ", "" + mEmailList);
// String[] test = mEmailList.indexOf(value);
fullName = mEmailList.get(index).get(TAG_FNAME) +
" " +
mEmailList.get(index).get(TAG_LNAME);
mPhoneNumber = mEmailList.get(index).get(TAG_PHONE);
mAddress = mEmailList.get(index).get(TAG_ADDRESS) + " " +
mEmailList.get(index).get(TAG_CITY) + " " +
mEmailList.get(index).get(TAG_STATE) + " " +
mEmailList.get(index).get(TAG_ZIP);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It looks like you want the index within the list that contains a map that has a specific email address as one of the values. For that purpose you need to call indexOf on the list, and pass to it a Map.
Something like : mEmailList.indexOf(map).
What you are doing is searching for the index of the first occurrence of a sub-string within another String. That won't give you an index within the list.
In addition, it looks like you are mixing the code that creates the list of maps with the code that searches the list for a specific email.
You are getting -1 because of
test2.indexOf("v8")
The ArrayList test2 contains arrays String[], it doesn't containg "v8". test2, for example, contains { "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8" }, but not "v8".
Note: The methods String#indexOf() and ArrayList#indexOf() are different, so you should read their specification before using them.

Categories

Resources