Convert list to array in java in another class - java

I have this code and I am new to this project so help me out this:
private List<DbParam> getCorrespondingDbParams(Map<String, Object> source, boolean continueOnKeyAbsent, CMetaBasicField...fields){
List<DbParam> dbParams = new ArrayList<>();
for (CMetaBasicField field : fields) {
String key = field.getKey();
if (!source.containsKey(key)) {
if(continueOnKeyAbsent){
continue;
} else {
return null;
}
}
dbParams.add(field.getDbParam(source.get(key)));
}
return dbParams;
}
and when dbParams go to getDbParam is type of List
default DbParam getDbParam(Object val) {
return new DbParam(new DbColumn(getDbField(), getFieldType()),val);
}
But I want to convert in array. How to do this?

I would recommend converting between an ArrayList and an array like this:
List<String> myArrayList = new ArrayList<String>();
String []myArray = new String[myArrayList.size()];
myArrayList.toArray(myArray);

You can convert a arraylist to an array by doing:
dbParam[] myArr= new dbParam[myList.size()];
myArr= myList.toArray(myArr);
so you should convert your list to arraylist

DbParam[] arr = list.toArray(new DbParam[list.size()]);

Related

Android-Java List to String and vice versa

I am new to Android programming and I wanted to create a function to take in a list and return a String. That's my code:
private String List_to_String(final ArrayList<String> list) {
String returnString = "{";
for (String _s : list) {
returnString = returnString + _s.replace(":","\\:") + ":";
}
if (returnString != null && returnString.length() > 0) {
returnString = returnString.substring(0,
returnString.length() - 1);
}
returnString = returnString.concat("}");
return returnString;
}
It works but now I want to make a function that returns a ArrayList when I give a String generated with the function above also I think you need to take extra care of the ":".
So if I have a String
HDJDJJDJ:JSJSJSJJSJS:SJJSHS\:\:JS
the function should return a list with these items
HDJDJJDJ
JSJSJSJJSJS
SJJSHS::JS
Can you understand me
Thanks for your help
Maybe you can try something like this.
In Android Studio
[File]->[Project Structure]->[Dependencies]->[Add Dependency]->[Library Dependency]-> choose 'app'(If you have multiple modules) -> search for 'GSON' -> choose implementation.
Initialize Gson in java class :
Private Gson gson = new Gson();
String to List :
List<T> myList = new ArrayList<T>();
String myString = gson.toJson(myList);
List to string :
Type myType = new TypeToken<List<T>>(){}.getType();
myList = gson.fromJson(myString, myType);

Type mismatch: cannot convert from String to List<String> attempting to populate a dropdown

I am attempting to populate a dropdown from the controller by passing the iteration value to a list. The iteration is done successfully but I keep getting a type mismatch error
List<Skills> mskills = skillsService.getAll();
for(Skills skills : mskills ){
String nameVal = skills.getName();
List<String> matchName = nameVal; //having an issue here
}
return matchName;
how can pass the value of nameVal to the matchName. Kindly assist
There are a few mistakes. matchName list is not visible out of the for loop. Further more, you can't assign a String to a List reference.
Replace your code with:
List<Skills> mskills = skillsService.getAll();
List<String> matchName = new ArrayList<String>();
for(Skills skills : mskills ){
String nameVal = skills.getName();
matchName.add(nameVal); //having an issue here
}
return matchName;
You're trying to assign a String object to a List<String> object. You need to create a list and then add elements to it.
List<Skills> matchName = new ArrayList<>();
List<Skills> mSkills = skillService.getAll();
for(Skill s : mSkills) {
String nameVal = skills.getName();
matchName.add(nameVal);
}
return matchName;
Try this:
List<String> matchName = new ArrayList<String>();
for(Skills skills : mskills ){
String nameVal = skills.getName();
matchName.add(nameVal); //having an issue here
}
return matchName;

How to convert Arraylist consisting of pojo class into array in java

I have a pojo class named "Performance" like this
public class Performance {
String productId;
String productBrand;
String productGraph;
//getters and setters
And I saved it to arraylist named "performanceList" like this:
JSONArray dataGraph=null;
JSONObject obj = new JSONObject(response);
dataGraph = obj.getJSONArray("product_list");
performanceList.clear();
for(int i=0;i<dataGraph.length(); i++){
JSONObject jsonObject = dataGraph.getJSONObject(i);
Performance performance = new Performance();
if(!jsonObject.isNull("id")){
performance.setProductId(jsonObject.getString("id"));
}
if(!jsonObject.isNull("brand")) {
performance.setProductBrand(jsonObject.getString("brand"));
}
if(!jsonObject.isNull("sales")){
performance.setProductGraph(jsonObject.getString("sales"));
}
performanceList.add(i, performance);
}
And now, can you please help me fetch the data from arraylist and be converted into array just like this
String []brand = {/*getProductBrand from arraylist*/};
String []id = {/*getProductId from arraylist*/};
String []id = {/*getProductGraph from arraylist*/};
Use foreach or for loop
String[] brand = new String[performanceList.size()];
for(int i=0;i<performanceList.size();i++)
{
brand[i] = performanceList.get(i).getBrand();
.....
......
}
Similary for other fields as well.
you could use stream.map() in java8
List<String> productBrands = performanceList
.stream()
.map(el-> el.getProductBrand())
.collect(Collectors.toList());
repeat same for el.getId() or any other data you need to collect from Performance objects

How to get the keys from a LinkedHasMap?

I have a code populating a listView:
JSONArray data = responseData.getJSONArray("data");
String[] values = new String[data.length()];//I wanna get rid of this
LinkedHashMap<String, String> helpData = new LinkedHashMap();
for (int i = 0; i < data.length() ; i++) {
String header = data.getJSONObject(i).getString("glossary_header");
String description = data.getJSONObject(i).getString("gloassary_description");
helpData.put(header, description);
values[i] = header;
Log.d("mylog", "counter" + i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
I want to pass the keys to Arrayadapter, I was hoping to find a getKeys() method that could magically return an array of key from the map.
KeySet() was close but did not work, what is the proper way to do this. I don't want to use string array. I want to have my pair values together.
You can get like this
Collection<String> values = helpData.keySet();
for (String string : values) {
//
}
Set<String> keys = myArray.keySet();
String[] keysAsArray = keys.toArray(new String[0]);
More detail on the toArray method can be found at http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray(T[])
for (final String key : helpData.keySet()) {
// print data...
}
or
final Iterator<String> cursor = helpData.keySet().iterator();
while (cursor.hasNext()) {
final String key = cursor.next();
// Print data
}

Convert normal Java Array or ArrayList to Json Array in android

Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?
If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
example key = "Name" value = "Xavier" and the value depends on number of array you pass in
try
{
JSONArray jArry=new JSONArray();
for (int i=0;i<3;i++)
{
JSONObject jObjd=new JSONObject();
jObjd.put("key", value);
jObjd.put("key", value);
jArry.put(jObjd);
}
Log.e("Test", jArry.toString());
}
catch(JSONException ex)
{
}
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
This is the correct syntax:
String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);
For a simple java String Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
My code to convert array to Json
Code
List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);
System.out.println(jray.toString());
output
["so 1","so 2","so 3"]
Convert ArrayList to JsonArray
: Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]

Categories

Resources