Putting multiple element from ArrayList to a single Array? - java

Need some help to understand how I can put all the elements from an ArrayList to a single Array. Not sure if its possible to do it in a single Array.
Declaration
List componentNameList = new ArrayList();
String[] componentNameItem = soapApiCall.getComponentNames();
componentNameList.add(Arrays.toString(componentNameItem));
Here is the element of the ArrayList:
[[Index, Pattern, Smart, Intell][Index, Tree, Pet, Intel][Index, Pattern, Bear, Intell, Dog][Sky, Intern, Blond]]
Expected output for the Array
<Index><Pattern><Smart><Intell><Index><Tree><Pet><Intel><Index><Pattern><Bear><Intell><Dog><Sky><Intern><Blond>
Thanks in advance.

First, I'd suggest you not use raw types, nor do I suggest to add the string representation of an array to a raw type list.
Thus, change this:
List componentNameList = new ArrayList();
to this:
List<List<String>> componentNameList = new ArrayList<>();
then change this:
componentNameList.add(Arrays.toString(componentNameItem));
to this:
componentNameList.add(new ArrayList<>(Arrays.asList(componentNameItem)));
Then you can accomplish the task at hand with streams like below:
String[] resultSet = componentNameList.stream()
.flatMap(List::stream) // flatten
.toArray(String[]::new); // collect to array
then print:
System.out.println(Arrays.toString(resultSet));

Related

How do I add an array into an arraylist (so that it becomes a 2D arraylist) in java?

I have an array:
String[] a = {"abc","def","ghi"}
Now I want to store this array into my string arraylist
ArrayList<String> arr = new ArrayList<>();
so that it becomes like this:
[["abc","def","ghi"]]
I have tried this code but it doesn't work:
arr.add(Arrays.asList(a));
Please help me
Since Arrays.asList(a) returns List, to add it to your list you need to use addAll()
arr.addAll(Arrays.asList(a));
Instead of
arr.add(Arrays.asList(a));
But the result will be ["abc","def","ghi"]
If you want to achieve this [["abc","def","ghi"]] then define your ArrayList as
List<List<String>> arr = new ArrayList<>();
using arralist addAll() method we can do but,
Using arrayList is depricated approach , use Streams instead of it:
System.out.println(Collections.singletonList(Stream.of(new String[] {"abc","def","ghi"}).collect(Collectors.toList())));
will result in:
[[abc, def, ghi]]

How can add an element to an array?

I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.

How to split a String to an ArrayList?

I know there is a String split method that returns an array but I need an ArrayList.
I am getting input from a textfield (a list of numbers; e.g. 2,6,9,5) and then splitting it at each comma:
String str = numbersTextField.getText();
String[] strParts = str.split(",");
Is there a way to do this with an ArrayList instead of an array?
You can create an ArrayList from the array via Arrays.asList:
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(textField.getText().split(",")));
If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):
List<String> parts = Arrays.asList(textField.getText().split(","));
There is no such thing as a Split functionfor list, but you can do the split and then convert to a List
List myList = Arrays.asList(myString.split(","));

Java add variable to string array

I have a small code that includes citynames which will be displayed.
Now a want a user can add names with a scanner, I know the code for the scanner but not how to add the variable.
Code I have:
String[] cityNames = { "Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" };
System.out.println(Arrays.toString(cityNames));
No you cannot do it with a Array since the size is fixed , once it declared.
You are probably looking for Collections. Prefer to Use List interface with ArrayList implementation.
The reason is that the ArrayList is
Resizable-array implementation of the List interface.
List<String> cityNames = new ArrayList<>();
Now you have methods like add, remove, ... and many more useful methods on your cityNames List
You can use a List<String>, get the input value and add it:
List<String> cities = new ArrayList<>();
cities.add(userInput);
List is better to use than array as its length is modifiable.
Arrays have a fixed length. If the amount of Strings in your collection is variable, you´ll have to use a List.
You can add new element to array if index of new element less than the size of array.
arr[i]="some value" // to do this i < arr.length
If array is completely filled with elements when you assign new value to index previous value will override. You can't add more elements than the size of declared since array has fixed size.
Array is fixed size so you can't add the value to it if the size is already filled. For dynamic array use List instead of array.
Do like this
List<String> list = new ArrayList<String>(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" ));
list.add("new value1");
list.add("new value2");
It's better to use there set, which excludes duplicate entries automatically:
Set<String> cities = new HashSet<String>();
cities.addAll(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren"));
then to add new city just call:
sities.add(newCity);
Scanner input = new Scanner(System.in);
List<String> cityNames = new ArrayList<String>();
//Add the city names to cityNames list...
cityNames.add(input.next());

Multi-dimensional Java ArrayList (Declared element syntax)

Is it possible to do the following?
private static ArrayList<integer<integer<String>>> myArrayList;
In other words, create an ArrayList with declared element syntax?
Example:
myArrayList[0][0] = "This is the string.";
If not, is it possible to do such with normal arrays?
It seems you are looking for multi-dimensional arrays in Java, declared as follows:
String [][] list = new String[10][10];
list[0][0] = "This is a string";
System.out.println(list[0][0]);
You can declare List of List in the following way: -
List<List<String>> listOfList = new ArrayList<List<String>>();
Initialize your List, and then to add a String to your list element: -
listOfList.add(new ArrayList<String>());
listOfList.get(0).add("my String");
You can do
List<List<String>> list = new ArrayList<List<String>>();
list.add(new ArrayList<String>());
list.get(0).add("This is the string");
What you would want to achieve in realtime?, Java defines set of APIs, which has its own usage and purpose. If you want to use multidimensional array, I would suggest to go for Object[][], though you should be able to declare
ArrayList list[][] = new ArrayList[5][7];
By doing so, you would be making you operation bit complex. And more over ArrayList is nothing but single dimensional Object array.
FYI
How to create a Multidimensional ArrayList in Java?

Categories