Can I name an array with a variable in java? [duplicate] - java

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 3 years ago.
for example I want to do this:
String[] arraynames = new String[2];
arraynames[0] = "fruits";
arraynames[1] = "cars";
and now I don't know how to do this
String[] arraynames[0] = new String[100]; // ??????
so that I create a String array called fruits with 100 cells...
I know this doesn't work but is there someway to do this?

Use an HashMap
Example:
HashMap<String,String[]> arraynames = new HashMap<String,String[]>();
arraynames.put("fruits", new String[1000]);
// then simply access it with
arraynames.get("fruits")[0] = "fruit 1";
However, may I suggest you replace arrays with ArrayList ?
HashMap<String,ArrayList<String>> arraynames = new HashMap<String,ArrayList<String>>();
arraynames.put("fruits", new ArrayList<String>());
// then simply access it with
arraynames.get("fruits").add("fruit 1");
** EDIT **
To have an array of float values instead of strings
HashMap<String,ArrayList<Float>> arraynames = new HashMap<String,ArrayList<Float>>();
arraynames.put("fruits", new ArrayList<Float>());
// then simply access it with
arraynames.get("fruits").add(3.1415f);

So, you are looking for a doubly indexed array?
Something like:
String[][] arraynames = String[2][100];
You have created an array of 2 arrays that contain 100 String elements each in this case.

I hope I get you right, you could something like this:
ArrayList arraynames = new ArrayList();
arraynames.add("fruits");
arraynames.add("cars");
arraynames.set(0, new ArrayList(100) );

I am not quite clear on the second line of code here. You said you are trying to create a string array named fruits. This should suffice if I understood this right.
String [] fruits = new String[100];

you should use a bi-dimensional array like this:
String[][] myData = new String[2][100];
now myData is an array with 2 elements, both of them are arrays of "100 cells", then you can use these 2 arrays as follows:
String[] fruits = myData[0];
String[] cars = myData[1];
fruits[0] = "peach";
cars[0] = "mustang";

Using Guava library:
ListMultimap<String,String> mappedItems = ArrayListMultimap.create();
mappedItems.put("Fruits","Apple");
mappedItems.put("Fruits","Orange");
mappedItems.put("Fruits","Banana");
mappedItems.put("Cars", "BMW");
mappedItems.put("Cars","Ferrari");
System.out.println(mappedItems);
Output:
{Cars=[BMW, Ferrari], Fruits=[Apple, Orange, Banana]}

You can use one of the following :
String[][] arraynames = String[2][100];
Map<String, String[]> namesMap = new HashMap<String, String[]>();
List<List<String>> names = new ArrayList<ArrayList<String>()>>();

Related

Comparing two ArrayLists and remove duplicates from original ArrayList

I have two Custom Arraylist:
List<Item> before = new ArrayList<Item>();
List<ItemEx> after = new ArrayList<ItemEx>();
before.add(new Item(1L,"test1"));
before.add(new Item(2L,"test2"));
before.add(new Item(3L,"test3"));
after.add(new ItemEx(1L,"test4"));
after.add(new ItemEx(2L,"test5"));
after.add(new ItemEx(4L,"test6"));
after.add(new ItemEx(5L,"test7"));
I want to store the elements in the List<ItemEx> after and the element shoulds be after the removing of common element is {3L, 4L, 5L}.
FYI
List<Item> & List<ItemEx> should be SAME TYPE .
Logic
List<String> before = new ArrayList<String>();
List<String> after = new ArrayList<String>();
List<String> list_checking = new ArrayList<String>(before);
list_checking.addAll(after);
List<String> list_common = new ArrayList<String>(before);
list_common.retainAll(after);
list_checking.removeAll(list_common);
Try this :
HashSet hs = new HashSet();
hs.addAll(before);
hs.addAll(after);
after.clear();
after.addAll(hs);
Now, in after list you get desire values.
Its simple. Take a copy of the existing one into a temporary Variable if you want for future use.
ArrayList temporiginalArrList=OriginalArrayList;
//here 'T' can be a specific object to want to save
OriginalArrayList.removeAll(secondArrayList);

Converting from String[] to Arraylist, removing elements and converting and back to String[]

String [] TxtStr = new String[] {"bob","alan", "sam"};
List<String> stringList = new ArrayList<String>(Arrays.asList(TxtStr));
String [] TxtStr2 = new String[] {"bob","alan"};
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr));
stringList.removeAll(stringList2);
String[] bTxtStr = stringList.toArray(new String[stringList.size()]);
String output = "nnn";
for (int x=0; x<bTxtStr.length; x++){
output +=bTxtStr[x];
}
Currently this is a small segment of an android project I'm working on where I have to compare the contents of 2 String[].
I've been having quite a few problems so I've started out with a simple case of 2 String[] with 2 and 3 elements respectively. After initializing the String[] I convert them to ArrayLists and perform the removeAll function, which ideally should remove the elements "bob" and "alan" from the first list and eventually the output.
BTW using remove to stringList.remove("bob") works in terms of eliminating that particular string from the ArrayList. Just wondering what I can do to ensure that stringList.removeAll(....) works.
Thanks for any help in advance.
you have bug in:
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr));
you should use TxtStr2:
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr2));
reomoveAll method of ArrayList definitely works fine. You have made mistake while creating second ArrayList.
For easy approach, you can use Java 8 Streams. Try the below code. It will give you directly single comma separated string. You can change separation character.
List<String> stringList = Arrays.asList("bob","alan", "sam");
List<String> stringList2 = Arrays.asList("bob","alan");
String mergedString = stringList.stream().filter(string ->!stringList2.contains(string)).collect(Collectors.joining(","));
System.out.println("Merged String: " + mergedString);
You might be ending up removing everything, because of your list creation which are based on same arrays. Change
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr);
to
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr2);

java - "int cannot be converted to ArrayList"

I'm trying to create a two dimensional ArrayList which will store ints, strings & booleans.
I've got as far as entering the first int, but I get a red squiggle and the error "int cannot be converted to ArrayList".
ArrayList[][] qarray= new ArrayList [10][5];
qarray[0][0]= 1;
BTW, googling the phrase "int cannot be converted to ArrayList" is giving me exactly six results.
The error is correct.
Your array type is ArrayList. You can insert only ArrayLists in that array.
If you want to store int's, your declaration should be.
int[][] qarray= new int [10][5];
And also, as someone commented, you cannot store strings and booleans in this array anymore.
ArrayList[][] qarray= new ArrayList [10][5];
Basically your code creates 2 dimensional array list objects (50 array list objects).
qarray[0][0]= 1;
And you are trying to assign integer, where you need to create a ArrayList object. It expects something like
qarray[0][0]= new ArrayList();
However this would not meet your objective. The following piece of code could meet your objectives:
ArrayList[] qarray = new ArrayList[10];
qarray[0]= new ArrayList();
qarray[0].add(1);
qarray[1]= new ArrayList();
qarray[1].add(true);
qarray[2]= new ArrayList();
qarray[2].add("hello");
Try like this:
List<Integer> qarray = new ArrayList<>();
qarray.add(1);
First I believe that you need array and not ArrayList. 2d array can be created as following.
int[][] arr = new int [10][10];
Your next problem is that you tried to assign int constant 1 to variable of other type. The following example shows how to assign int to element of array
arr [0][0] = 1;
According to javadoc, you can not create arrays of ArrayList. Use 2D array instead.
If you need 2D ArrayList anyway, you should have tried this way:
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<>();
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(5);
listOfLists.add(list1);
listOfLists.add(list2);
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
you wan to add int,String and boolean then you can use
ArrayList<ArrayList<Object>> listOfLists = new ArrayList<ArrayList<Object>>();
it will help you
ArrayList<Integer>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add(new Integer(10);
try like this.

How to name a variable dynamically? - Java [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 9 years ago.
I want to know how I can name a variable dynamically.
If there are 3 items in a list then it should create 3 different object for each item.
Like:
ArrayList<String> list1;
ArrayList<String> list2;
ArrayList<String> list3;
So it should count up or anything like that.
if there are 4 items in a list it should create 4 variables.
How can I achieve that?
Edit:
I tried this but it says me an error that I can't create a generic array of Info.
ArrayList<Info> listForLg[] = new ArrayList<Info>[];
for (int i = 0; i < sizeOfKfzList; i++) {
listForLg[i] = new ArrayList<Info>();
listForLg[i].add(logInfo);
}
Can you help me?
Use arrays
ArrayList<String> list[] = new ArrayList<String>[3]; //or 4 or n
Then access them like
list[0] = "123";
Use Array for this...
ArrayList<String> yourlist[] = new ArrayList<String>([your size here])
Based on index use your variable..
yourlist[0] yourlist[1]....and so on
Hope this could help
Create list or arraylist
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>(4);
or
List<List<String>> group1 = new ArrayList<List<String>>(4);
Edit:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
To add (u can add items dynamically by loop)
group.add(list1);
and to get
list2= group.get(0);

How to combine two list string into one list

I have two list string different,
List<String> A= [1,2,3,4];
List<String> B= [1,2,5,6];
And I want to combine two list, in new list string in
List C = new Arraylist ();
how to combine two list string , be like the example:
C = [1,2,3,4,5,6];
Use Collection.addAll(), and a TreeSet, to remove duplicates and keep the result sorted.
Set<String> c = new TreeSet<String>(a); //create a Set with all the elements in a
c.addAll(b); //add all the elements in b
This will get them combined
combined = new ArrayList<String>();
combined.addAll(A);
combined.addAll(B);
This will get the uniques
List<String> uniques = new ArrayList<String>(new HashSet<String>(combined));
Do it like this :
listOne.removeAll(listTwo);
listTwo.addAll(listOne);
Collections.sort(listTwo);
You can remove the third line if you do not want it to be sorted.
Declaration of A and B seems to be wrong.
However, given two lists A and B, to combine them into C, you can use the following code:
C.addAll(A);
C.addAll(B);
Set<String> set = new TreeSet<String>(A); // for keeping the output sorted else you can also use java.util.HashSet
set.addAll(B);
List<String> finalList = new ArrayList<String>(set);
There are two ways to merge the results of both lists: using List#addAll or Set#addAll. The main difference between both is heavily explained here: What is the difference between Set and List?
Based on your request, you should merge both lists without repeating the items using a Set
List<String> lstA = new ArrayList<String>();
lstA.add("1");
lstA.add("2");
lstA.add("3");
lstA.add("4");
List<String> lstB = new ArrayList<String>();
lstA.add("1");
lstA.add("2");
lstA.add("5");
lstA.add("6");
Set<String> lstC = new LinkedHashSet<String>();
lstC.addAll(A);
lstC.addAll(B);
List<String> lstAB = new ArrayList(lstC);
List<String> A= new ArrayList<String>();
List<String> B= new ArrayList<String>();
Set<String> set = new TreeSet<String>(A);
set.addAll(B);
System.out.println(new ArrayList<String>(set));
To get a List<String> in sorted order, use this piece of code
String a[] = {"1","2","3","4"};
String b[] = {"1","2","5","6"};
List<String> A= Arrays.asList(a);
List<String> B= Arrays.asList(b);
Set<String> CTemp = new TreeSet<>();
CTemp.addAll(A);
CTemp.addAll(B);
List<String> C = new ArrayList<>(CTemp);

Categories