Manipulation of Java String arrays - java

I have a situation like
String[] ids = new String[depts.size()];
for (int i=0; i<ids.length; i++)
{
ids [i] = ("Dept" + .... )
}
So the loop looks at ids whose length is set to depts.size. But I need to add another string item to ids [i] like a "Region" + reg_num. Like the next item in ids[i] must be "Region" + reg_num and this is repeated for every department.
Since it is controlled by length, how do I do that? How do I adjust the loop to take 1 additional item. Any suggestions will be appreciated.
Thanks.

Just use a List instead of an array. Unlike arrays, lists are dynamically resizable:
final List<String> newList = new ArrayList<>(oldList);
newList.add(newElement);
EDIT if you are still using Java 6 you'll have to:
final List<String> newList = new ArrayList<String>(oldList);
instead
EDIT 2 depending on your use case, you may not even need a second list; as lists are dynamically resizable, unless you absolutely need to copy it, just keep the same list:
// first call
list.add(something);
// second call
list.add(somethingElse);
// etc etc
Without seeing more of the code however, it's hard to tell.

If you know before hand then initialize the array accordingly and add the elements as:
String[] ids = new String[depts.size()+1];//added one in the length
for (int i=0; i<ids.length; i++)
{
ids [i] = ("Dept" + .... )
}
ids[ids.length-1] = "Region"+....;
or
String[] ids = new String[2*depts.size()];//added one in the length
for (int i=0; i<ids.length; i=i+2)
{
ids [i] = ("Dept" + .... )
ids[i+1] = "Region"+....;
}

If you are trying to store a department for each id then its better to define a custom class like this:
public class Region {
String id;
String dept;
public Region(String id, String dept) {
this.id=id;
this.dept=dept;
}
// getters for id and dept
}
then define your region array like this
Region[] regions = new Region[depts.size()];
for (int i=0; i<regions.length; i++) {
regions[i] = new Region("Dept"+i, "Region"+i);
}

If I understand your reqs correctly, you can do something like this (but remember that you can hold a list of strings instead of an array, to change it dynamically):
String[] ids = new String[depts.size()*2];
for (int i=0; i<ids.length; i+=2)
{
// depts index would be i/2
ids [i] = ("Dept" + .... )
ids[i+1] = "Region"; // + ...
}

Related

how to get two string array item position and store in each separate string array in android

Sorry for my bad English. I am using two separate string array for each item of arraylist. All things working fine . My Question is I want to take each item of String array (say) if i take string array "asasaqty" and another item of string array "asasaId" then I want to store each item of string array value in third string array (say:[id1,qty1] and so on). Please let me know if there is a proper solution for this.
Below is my code.
Thanks in advance
String [] asasaqty;
String [] asasaId;
final AddToCartData addToCartData = response.body();
shoppingBagArrayList = addToCartData.getData();
asasaqty = new String[shoppingBagArrayList.size()];
asasaId = new String[shoppingBagArrayList.size()];
for (int i = 0; i < shoppingBagArrayList.size(); i++) {
asasaqty[i] = shoppingBagArrayList.get(i).getQty();
asasaId[i]=shoppingBagArrayList.get(i).getProductId();
System.out.println("==========wwwww========"+ Arrays.toString(asasaqty));
System.out.println("======wwwwssssswwwwss======"+ Arrays.toString(asasaId));
/* HashMap<String,String> map=new HashMap<String,String>();
for (int i = 0; i < asasaqty.length; i++) {
map.put(asasaqty[i],asasaId[i]);
System.out.println("======aaaaaaa======"+ map.put(asasaqty[i],asasaId[i]));
}*/
After printing the value in logcat the value is looking like
/System.out: ==========wwwww========[3, 2]
/System.out: ======wwwwssssswwwwss======[151, 10]
Now i want to take another String array and store each item asasaqty and asasaId in separate array like below
String[] xyz = [3,151] and
String[] abc = [2,10]
Please let me know how can we do this.
You can use productID and key (Assuming it is unique) and qty as value.
HashMap<Integer,Integer> dataMap = new HashMap<>();
for (int i=0; i <shoppingBagArrayList.size; i++){
dataMap.put(shoppingBagArrayList.get(i).getProductId() , shoppingBagArrayList.get(i).getQty());
}
System.out.println("DataMap: "+dataMap);

Add elements to a list and separate each element by a colon ":" instead of a comma

I have the below three elements :
play_full_NAME=556677
pause_full_NAME=9922
stop_full_NAME=112233
A string "abc" returns all the above three elements one by one from a particular piece of code.
I am trying to add all three elements in a list separated by a colon ":"
Sample output :
play_full_NAME=556677:pause_full_NAME=9922:stop_full_NAME=112233
My attempt:
List<String> list = new ArrayList<String>();
list.join(":",abc)
Please help with a better way to handle this.
Your understanding about List is little flawed. Comma is only printed for representation purposes.
To join strings with colon, you can do the following
List<String> list = Arrays.asList("play_full_NAME=556677",
"pause_full_NAME=9922",
"stop_full_NAME=112233");
String joinedString = String.join(":", list);
Did you really understood the List well?
In fact, there is no separator, each item / value is stored as different "object".
So you have some amount of independent values- Strings in this case, what can you see on screenshot bellow, or if you will do System.out.println(someList); it will call override of method toString() which is inherited from Object class , which is root parent class of all classes in Java.
So its absolutely nonsense to add some split character between each items in List, they are split already, you can access each item by get(int position) method.
So if you want to print each item of list "by yourself", can be done like follows:
for (int i = 0; i < someList.size(); i++) {
System.out.println(i + " = " + someList.get(i));
}
/* output will be
1 = 1 item
2 = 2 item
3 = 3 item
4 = 4 item
*/
If you want to implement custom method for printing "your list" then you can extend eg. ArrayList class and override toString method, but better and more trivial approach will be prepare some method in some utils to get formatted String output with context of List- eg. (notice there will be ; after last element)
public static String getFormatStringFromList(ArrayList<String> data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
sb.append(data.get(i) + ";");
}
return sb.toString();
//eg. 0 item;1 item;2 item;3 item;4 item;
}
To avoid last separator you can do eg. simple check
public static String getFormatStringFromListWitoutLastSeparator(List<String> someList) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < someList.size(); i++) {
sb.append(someList.get(i));
if(i < someList.size() -1) {
sb.append(";");
}
}
return sb.toString();
//0 item;1 item;2 item;3 item;4 item
/*
someList[0] = 0 item
someList[1] = ;
someList[2] = 1 item
someList[3] = ;
{etc..}
*/
}
The best approach to get String from list will be like #krisnik advised:
String joinedString = String.join(":", list);
You would need to add the colon elements separately if you want them to be within your list.
For example:
List<String> list = new ArrayList<String>();
list.add(abc);
list.add(":");
list.add(def);
list.add(":");
and so on.
I would recommend against this, however, as you can simply format the output string using String.format or a StringBuilder when you need it.

JAVA Get each value of arraylist

I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}

Java, how to adjust second dimension of 2 dimensional array?

In my application I need to have a 2 dimensional array. If I define it fix it works fine, like this:
static final String arrGroupelements[] = {"India", "Australia", "England", "South Africa"};
static final String arrChildelements[][] = { {"Sachin Tendulkar", "Raina", "Dhoni", "Yuvi" },
{"Ponting", "Adam Gilchrist", "Michael Clarke"},
{"Andrew Strauss", "kevin Peterson", "Nasser Hussain"},
{"Graeme Smith", "AB de villiers", "Jacques Kallis"} };
However, in my code I have two lists. the first is list of recipe name that i can get it.
LinkedList<String> recipeList = dbShoppingHandler.getAllRecipeNames();
String arrGroupelements[] = new String[recipeList.size()];
for(int i=0; i<recipeList.size(); i++) {
arrGroupelements[i] = recipeList.get(i);
}
My second list is list of ingredients. In order to get list of ingredients i need to set recipe name and then i can get the list. However, i don't know how put this list as second dimension. my code is like this:
String arrChildelements[][] = new String[recipeList.size()][20];
for(int i=0; i<recipeList.size(); i++) {
LinkedList<String> ingredient = dbShoppingHandler.getIngredientsOfRecipeName(recipeList.get(i));
for(int j=0; j<ingredient.size(); j++) {
arrChildelements[i][j] = ingredient.get(j);
}
}
Bad thing is, i need to set a number (in my case 20) for second dimension. If i do like this for lists that have 5 items i will have 15 " " elements and those have more than 20 items the code ignore them.
First dimension is fix but i need to adjust second dimension based on number of ingredients.
any suggestion are appreciated. thanks.
How about assigning an array in the desired sise:
String arrChildelements[][] = new String[recipeList.size()][];
// not mentioning second dimension size ^^
for(int i=0; i<recipeList.size(); i++) {
LinkedList<String> ingredient = dbShoppingHandler.getIngredientsOfRecipeName(recipeList.get(i));
arrChildelements[i] = String[ingredient.size()];
// assigning new array here ^^
for(int j=0; j<ingredient.size(); j++) {
arrChildelements[i][j] = ingredient.get(j);
}
}
I suggest not to use 2D arrays for dynamic structures. Arrays are immutable, so you have to copy them, create gaps and move elements around. The standard Java library doesn't offer many useful methods to do that.
Instead, use a list of lists:
List<List<String>> data = new ArrayList<List<String>>();
Lists have many useful methods to append elements, insert and remove them and they will make you life much easier.
The simplest way to to not assume you know the length in advance.
String[][] arrChildelements[] = new String[recipeList.size()][];
for(int i=0; i<recipeList.size(); i++) {
List<String> ingredient = dbShoppingHandler.getIngredientsOfRecipeName(recipeList.get(i));
arrChildelements[i] = ingredient.toArray(new String[0]);
}

How to combine 2 Vectors in a JList?

Vector<String> totalProducts = Products.getProductNames();
Vector<String> selectedProducts = Products.getSelectedProductNames();
The selectedProducts vector is a subvector of totalProducts (meaning that selectedProducts contains one, more or all of the elements from totalProducts). What I want is to combine these two vectors and make a single JList, which contains all the elements from totalProducts, and with the elements of selectedProducts already selected.
What I tried:
Vector<Integer> indices = new Vector<Integer>();
JList prdList = new JList(totalProducts);
for(int i = 0; i < totalProducts.size(); i++)
{
for(String name : selectedProducts)
{
if(totalProducts.contains(name)) indices.add(i);
}
}
Object [] objIndices = indices.toArray();
//... Cast from Object [] to int [] ....
prdList.setSelectedIndices(intIndices);
...but this selects all the elements in the final JList.
Previously I tried:
JList prdList = new JList(totalProducts);
for(String tName : totalProducts)
{
for(String sName : selectedProducts)
{
if(totalProducts.contains(sName)) prdList.setSelectedValue(sName, false);
}
}
...but this one selected only the last element from the selectedProducts.
Can you please help me to do it right?
Your attempt that selects all items does so because you're iterating over each item, and if any item from the selectedProducts list is in the total list, adds the iteration item's index to the final selection list. Try changing your loop to something like this:
for(int i = 0; i < totalProducts.size(); i++)
{
String name = totalProducts.get(i);
if(selectedProducts.contains(name)) indices.add(i);
}
in debugging your first attempt (which looks like it should work, what was the contents of your intIndices array? because that looks like it should work, presuming your array conversion works.
however, since selectedproducts is guaranteed to be less items than total, you might want to iterate over that instead?
List<Integer> indices = new ArrayList<Integer>(selectedProducts.size());
for(String name : selectedProducts)
{
int index = totalProducts.indexOf(name);
if (index != -1)
indices.add(index);
}
although, since indexOf is a linear search through a list, it probably doesn't make much of a difference either way.
as for your second attempt, the ListSelectionModel has methods for adding a selected index (addSelectionInterval(int index0, int index1))
, you're using the one that sets (overwrites) the selection.
see http://download.oracle.com/javase/6/docs/api/javax/swing/ListSelectionModel.html
aside: you might want to use List<> instead of Vector<>, as vector has a lot of unecessary synchronization overhead. Unless you need the synchronization....
edit fixed copy+paste of add(i) with add(index)

Categories