I have the following code snippet:
//create map array and fill it with 3 dummy maps
Map[] mapArr= new Map[3];
for(int i = 0; i < mapArr.length; i++)
{
Map map = new HashMap();
mapArr[i] = map;
}
//now remove the second element (index == 1) from the map array
mapArr = ArrayUtils.removeElement(mapArr, 1);
My problem is witht he final line of code, because no matter what I try I get the error
Type mismatch: cannot convert from Object[] to Map[]
How do I convert the Object[] returned by removeElement() into a Map[]?
Did you try to cast it to "Map[]" ?
mapArr = (Map[]) ArrayUtils.removeElement(mapArr, 1);
Related
I can't to take value from dataF when I use map.put that say error.if I replace map.put("Nos",dataF); to map.put("Nos",dataF[arrLength]) It's work but It's return [Ljava.lang.string;#b1f37df0
ArrayList<HashMap<String,String[]>> ArrList = new ArrayList<HashMap<String,String[]>>();
Intent intent = getIntent();
String[] dataF = intent.getStringArrayExtra("Money");
ListView list1 = (ListView)findViewById(R.id.listView1);
int arrLength = dataF.length;
for(int i=0;i<arrLength;i++)
{
HashMap<String, String[]> map = new HashMap<String, String[]>();
map.put("Nos", dataF[arrLength]); // << error
ArrList.add(map); // << error
}
ListAdapter adapters = new SimpleAdapter(resultActivity.this,ArrList,
R.layout.activity_column,
new String[] {"Nos"},new int[] { R.id.textView1});
list1.setAdapter(adapters);
you try put map.put("Nos", dataF[arrLength]); as HashMap<String, String[]> but dataF[arrLength] is a one String and your hashmap need one Array of String.
you can change that to:
map.put("Nos", dataF);
if you solve this i think next line is solved too.
and with dataF[arrLength] you must get ArrayIndexOutOfBounds because last index of your array is dataF[arrLength - 1]
UPDATE
with your say on comment i think you try show hashMpa.getValue(); but your value is array of String so you need show one index of that like hashMpa.getValue()[0];
you need following for showing values:
String[] value = hashMap.getValue();
for ( int i = 0 ; i < value.lenght() ; i++)
Log.d("index "+i , value[i]);
Update the code as below::
HashMap<String, String[]> map = new HashMap<String, String[]>();
map.put("Nos", dataF); // Pass the Array instead String
ArrList.add(map);
I want to parse following JSON array and store in array list.
[{"type":{"Male":"1","Female":"2"}}]
I have tried following code
JSONObject object=getJSONObject(0).getString("type");
Result:
{"Male":"1","Female":"2"}
Here type is the key and others are values.
It comes with comma, quotes.How to store this values are in ArrayList?
Something like the below should do the trick for your JSON. Seeing your JSON I don't see an Array anywhere.
String resultJson; // Assuming this has the JSON given in the question.
JSONObject object = new JSONObject(resultJson);
JSONObject type = object.getJSONObject("type"); //Get the type object.
HashMap<String, Integer> map = new HashMap<String, Integer>(); //Creating the Map
String male = type.getString("male"); //Get the male value
String female = type.getString("female"); //Get the female value
map.put("male", Integer.parseInt(male));
map.put("female", Integer.parseInt(female));
Something like this?
ArrayList<String> list = new ArrayList<String>();
if (jsonArray != null) { //In this case jsonArray is your JSON array
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
Say I have a hashmap with String type as key and ArrayList type as value, example {"value1"=["one","three","five"], "value2"=["two","four","six"]} where "value1" and "value2" are keys. I want to write the above hashmap data in following format. (so that I can read the csv file in excel)
value1,value2
one,two
three,four
five,six
My idea was to write the first key and its values as follows
value1
one
three
five
Then I was thinking of using the seek method in RandomAccessFile class to back to line 1 and again write the second key and its values. However I am not able to accomplish this task since seek function takes in the length of strings in the entire file and writes the new string after it. While I wanted the pointer to jump to the first line and append the string. Is there a better way to do this?. A quick example would be much appreciated.
Thanks
Why can't you just use 4 Strings, one for each row? Something like this:
StringBuilder keyRow = new StringBuilder();
StringBuilder value1 = new StringBuilder();
StringBuilder value2 = new StringBuilder();
StringBuilder value3 = new StringBuilder();
Iterator keys = hashmap.keySet().iterator();
boolean notFirst = true;
while(keys.hasNext()) {
String key = (String)keys.next();
ArrayList list = (ArrayList)hashmap.get(key);
if(!notFirst) {
keyRow.append(",");
value1.append(",");
value2.append(",");
value3.append(",");
}
keyRow.append(key);
value1.append((String)list.get(0));
value2.append((String)list.get(1));
value3.append((String)list.get(2));
notFirst = false;
}
Then at the end, just take the 4 Strings
String csv = keyRow.toString()+"\n"+value1.toString()+"\n"+value2.toString()+"\n"+value3.toString();
Note that this example isn't really proper CSV. Strings with commas aren't wrapped in quotes.
Or you iterate through the HashMap a thousand times if you have thousands of these rows. To save a bit of time from looking up a key, you can put them all in an ArrayList:
StringBuilder csv = new StringBuilder();
int row = 0;
ArrayList<ArrayList> list = new ArrayList<ArrayList>();
// Write the keys row:
Iterator keys = hashmap.keySet().iterator();
boolean notFirst = true;
while(keys.hasNext()) {
String key = (String)keys.next();
ArrayList tmp = (ArrayList)hashmap.get(key);
if(!notFirst) {
csv.append(",");
}
csv.append(key);
// store list
list.add(tmp);
notFirst = false;
}
csv.append("\n");
// Write the rest of the rows
while(row<numberOfTotalRow) {
notFirst = true;
for(int x=0;x<list.size();x++) {
if(!notFirst) {
csv.append(",");
}
csv.append((String)list.get(x).get(row));
notFirst = false;
}
row++;
}
You can make a method that prints out the map as you wish:
public void toString(HashMap<String, ArrayList<String>> map) {
for(int i = 0; i < map.size(); i++) {
ArrayList<String> list = new ArrayList<String>(map.keySet());
String key = list.get(i);
System.out.println(key);
for(int j = 0; j < map.get(key).size(); j++)
System.out.println(map.get(key).get(j));
}
}
The way you have imagined is impossible. A file is a continuous stream of bytes. So after you write the first value, you have this in your file : "value1\none\nthree\nfive". If you then seek to position 6 (after "value") and insert new characters, you'll be overwiting the first value's second row. The following bytes won't be magically pushed away.
The only way to do this is to traverse the data you have in a way that allows you to output the bytes in the same order that they will be in the file. So: go to each value and write the first element, to each value again and write their second element and so on.
You don't need a RandomAccessFile file, better use this:
HashMap<String, ArrayList<String>> map = new HashMap<>();
map.put("a", new ArrayList<>(Arrays.asList(new String[]{"A1", "A2", "A3"})));
map.put("b", new ArrayList<>(Arrays.asList(new String[]{"B1", "B2", "B3"})));
map.put("c", new ArrayList<>(Arrays.asList(new String[]{"C1", "C2", "C3"})));
{
/**
* Set your file printstream. For testing System.out
*/
PrintStream ps = System.out;
boolean first = true;
/**
* Size of the array list. Let's asume that the arraylist are of the
* same lenght;
*/
int s = 0;
/**
* Create a ArrayList variable because, this map class makes no guarantees
* as to the order of the map; in particular, it does not guarantee that
* the order will remain constant over time.
*/
ArrayList<Entry<String, ArrayList<String>>> l =
new ArrayList<>(map.entrySet());
for (Entry<String, ArrayList<String>> e : l) {
if (first) {
first = false;
s = e.getValue().size();
} else {
ps.print(",");
}
ps.print(e.getKey());
}
ps.println();
for (int i = 0; i < s; i++) {
first = true;
for (Entry<String, ArrayList<String>> e : l) {
if (first) {
first = false;
} else {
ps.print(",");
}
ps.print(
e.getValue().get(i));
}
ps.println();
}
}
Output:
b,c,a
B1,C1,A1
B2,C2,A2
B3,C3,A3
How would I convert
List list= new ArrayList();
to
String [] profArr= {};
I have tried doing
profArr = list.toArrary()
and
profArr = (String [])list.toArrary()
I get the following error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
I also have tried
String [] profArr= (String [])list.toArray(new String[0]);
and I get this error: The requested resource () is not available.
Here is how I create the list:
static List decode(int x)
{
List power2List = new ArrayList();
if (x < 0)
throw new IllegalArgumentException("Decode does not like negatives");
while (x > 0)
{
int p2 = Integer.highestOneBit(x);
x = x - p2;
power2List.add(p2);
}
return power2List;
}
List list= new ArrayList();
list= decode(rset.getInt("favprofs")); //rset being a result set which pulls one int
You need to be using list.toArray(new String[list.size()]). An Object[] is not type compatible with String[], despite every element in the Object[] being a String. Also, you should consider specifying the type parameter of your List to maintain type safety.
Basically you need to use
String profArr = list.toArray( < String array > (size))
you can use java collector
List<Tuple2<String, Boolean>> paras_check
String miss_params= paras_check.stream().map(e->e._1)
.reduce(",",(x,y)->(x+y));
I need to convert a navigable map to a 2d String array.Below given is a code from an answer to one of my previous question.
NavigableMap<Integer,String> map =
new TreeMap<Integer, String>();
map.put(0, "Kid");
map.put(11, "Teens");
map.put(20, "Twenties");
map.put(30, "Thirties");
map.put(40, "Forties");
map.put(50, "Senior");
map.put(100, "OMG OMG OMG!");
System.out.println(map.get(map.floorKey(13))); // Teens
System.out.println(map.get(map.floorKey(29))); // Twenties
System.out.println(map.get(map.floorKey(30))); // Thirties
System.out.println(map.floorEntry(42).getValue()); // Forties
System.out.println(map.get(map.floorKey(666))); // OMG OMG OMG!
I have to convert this map to a 2d String array:
{
{"0-11","Kids"},
{"11-20","Teens"},
{"20-30","Twenties"}
...
}
Is there a fast and elegant way to do this?
Best bet is just to iterate through the Map and create an array for each entry, the troublesome part is generating things like "0-11" since this requires looking for the next highest key...but since the Map is sorted (because you're using a TreeMap) it's no big deal.
String[][] strArr = new String[map.size()][2];
int i = 0;
for(Entry<Integer, String> entry : map.entrySet()){
// current key
Integer key = entry.getKey();
// next key, or null if there isn't one
Integer nextKey = map.higherKey(key);
// you might want to define some behavior for when nextKey is null
// build the "0-11" part (column 0)
strArr[i][0] = key + "-" + nextKey;
// add the "Teens" part (this is just the value from the Map Entry)
strArr[i][1] = entry.getValue();
// increment i for the next row in strArr
i++;
}
you can create two Arrays, one with the keys and one with the values in an "elegant way" then you can construct an String[][] using this two arrays.
// Create an array containing the values in a map
Integer[] arrayKeys = (Integer[])map.keySet().toArray( new Integer[map.keySet().size()]);
// Create an array containing the values in a map
String[] arrayValues = (String[])map.values().toArray( new String[map.values().size()]);
String[][] stringArray = new String[arrayKeys.length][2];
for (int i=0; i < arrayValues.length; i++)
{
stringArray[i][0] = arrayKeys[i].toString() + (i+1 < arrayValues.length ? " - " + arrayKeys[i+1] : "");
stringArray[i][1] = arrayValues[i];
}