Array structure in java - java

Can I create an array like this in java???
Array
([0]
array
[items1] = "one"
[items2] = "two"
[items3] = "three")
([1]
array
[items1] = "one###"
[items2] = "two###"
[items3] = "three#")
Thanx for your help

Yes, you can do this by creating an array of arrays. For example:
String[][] twoDimensionalPrimitiveArray = {
{"one", "two", "three"},
{"one###", "two###", "three###"}
};
You can also do this with the collection types:
List<List<String>> listOfLists = new ArrayList<>();
listOfLists.add(createList("one", "two", "three"));
listOfLists.add(createList("one###", "two###", "three###"));
// ...
private static List<String> createList(String... values) {
List<String> result = new ArrayList<>();
for (String value : values) {
result.add(value);
}
return result;
}
Edit
#immibis has rightly pointed out in the comments that createList() can be written more simply as new ArrayList(Arrays.asList(values)).

Yes, you can define an array of arrays:
String[][] arrayOfArrays = new String[2][]; // declare and initialize array of arrays
arrayOfArrays[0] = new String[3]; // initialize first array
arrayOfArrays[1] = new String[3]; // initialize second array
// fill arrays
arrayOfArrays[0][0] = "one";
arrayOfArrays[0][1] = "two";
arrayOfArrays[0][2] = "three";
arrayOfArrays[1][0] = "one###";
arrayOfArrays[1][1] = "two###";
arrayOfArrays[1][2] = "three#";
And to test it (print values):
for (String[] array : arrayOfArrays) {
for (String s : array) {
System.out.print(s);
}
System.out.println();
}

For two dimension arrays in Java you can create them as follows:
// Example 1:
String array[][] = {"one", "two", "three"},{"one###", "two###", "three###"}};
Alternatively you can define the array and then fill in each element but that is more tedious, however that may suit your needs more.
// Example 2:
String array[][] = new String[2][3];
array[0][0] = "one";
array[0][1] = "two";
array[0][2] = "three";
array[1][0] = "one###";
array[1][1] = "two###";
array[1][2] = "three#";

String[] twoDArray[] = {{"one", "two", "three"}, {"one###", "two###", "three###"}};

Related

Converting Arraylist to an Array [duplicate]

How might I convert an ArrayList<String> object to a String[] array in Java?
List<String> list = ..;
String[] array = list.toArray(new String[0]);
For example:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.
Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Java 11+:
String[] strings = list.toArray(String[]::new);
Starting from Java-11, one can use the API Collection.toArray(IntFunction<T[]> generator) to achieve the same as:
List<String> list = List.of("x","y","z");
String[] arrayBeforeJDK11 = list.toArray(new String[0]);
String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray
You can use the toArray() method for List:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = list.toArray(new String[list.size()]);
Or you can manually add the elements to an array:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Hope this helps!
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class);
Using copyOf, ArrayList to arrays might be done also.
In Java 8:
String[] strings = list.parallelStream().toArray(String[]::new);
In Java 8, it can be done using
String[] arrayFromList = fromlist.stream().toArray(String[]::new);
If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:
List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);
There are a few more preallocated empty arrays of different types in ArrayUtils.
Also we can trick JVM to create en empty array for us this way:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static import
String[] array = list.toArray(toArray());
But there's really no advantage this way, just a matter of taste, IMO.
You can use Iterator<String> to iterate the elements of the ArrayList<String>:
ArrayList<String> list = new ArrayList<>();
String[] array = new String[list.size()];
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
array[i] = iterator.next();
}
Now you can retrive elements from String[] using any Loop.
Generics solution to covert any List<Type> to String []:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString() method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String [] strArry= list.stream().toArray(size -> new String[size]);
Per comments, I have added a paragraph to explain how the conversion works.
First, List is converted to a String stream. Then it uses Stream.toArray to convert the elements in the stream to an Array. In the last statement above "size -> new String[size]" is actually an IntFunction function that allocates a String array with the size of the String stream. The statement is identical to
IntFunction<String []> allocateFunc = size -> {
return new String[size];
};
String [] strArry= list.stream().toArray(allocateFunc);
List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
array[i++] = s;
}
in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:
import java.util.ArrayList;
import java.lang.reflect.Array;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
Integer[] arr = convert(al, Integer.class);
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
public static <T> T[] convert(ArrayList<T> al, Class clazz) {
return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
}
}
In Java 11, we can use the Collection.toArray(generator) method. The following code will create a new array of strings:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
from java.base's java.util.Collection.toArray().
You can convert List to String array by using this method:
Object[] stringlist=list.toArray();
The complete example:
ArrayList<String> list=new ArrayList<>();
list.add("Abc");
list.add("xyz");
Object[] stringlist=list.toArray();
for(int i = 0; i < stringlist.length ; i++)
{
Log.wtf("list data:",(String)stringlist[i]);
}
private String[] prepareDeliveryArray(List<DeliveryServiceModel> deliveryServices) {
String[] delivery = new String[deliveryServices.size()];
for (int i = 0; i < deliveryServices.size(); i++) {
delivery[i] = deliveryServices.get(i).getName();
}
return delivery;
}
An alternate one-liner method for primitive types, such as double, int, etc.:
List<Double> coordList = List.of(3.141, 2.71);
double[] doubleArray = coordList.mapToDouble(Double::doubleValue).toArray();
List<Integer> coordList = List.of(11, 99);
int[] intArray = coordList.mapToInt(Integer::intValue).toArray();
and so on...

How to get String[] A - String[] B i.e. all elements which are in A but not in B ,In java?

I have a String [] allEmps ; String array Of All emps;
String [] allEmps = StringUtil.convertCommaStringToArray(listOfEmpsCommaSep, ",");
I have another String [] EmpsWithCompensationDefined
String [] listOfEmpsWithCompDefined = DBUtility.selectFieldAndReturnAsStringArray(QueryToGetEmpsWhomCompIsDefined, con);
Now I want to get employees whom compensation is not defined i.e An entry which is in A but not in B.
Solution : I can iterate over both the array and get the difference. But this would be O(n^2) complex. Is there any other way with less asymptotic complexity?
Edit:
ArrayList listOfFilteredEmps = new ArrayList();
for(int j =0;j<allEmps.length;j++){
boolean isMatched = false;
for(int i=0;i<listOfEmpsWithCompDefined.length;i++){
if(allEmps[j]==listOfEmpsWithCompDefined[i]){
isMatched = true;
}
}
if(!isMatched){
if(listOfFilteredEmps!=null && listOfFilteredEmps.size()==0){
listOfFilteredEmps.add(allEmps[j]);
}else{
listOfFilteredEmps.add(","+allEmps[j]);
}
}
}
You can try in this way
String [] allEmps={"A","B","C","D"};
String [] listOfEmpsWithCompDefined={"A","D","E"};
Set<String> mySet1 = new HashSet<>(Arrays.asList(allEmps)); // convert to set
Set<String> mySet2 = new HashSet<>(Arrays.asList(listOfEmpsWithCompDefined));
mySet1.removeAll(mySet2);// elements which are in A but not in B
String[] df = mySet1.toArray(new String[mySet1.size()]);// difference

Java convert ArrayList<String[]> to String[][]

Do I have to loop through each element to convert ArrayList<String[]> to String[][] or is there a more efficient way?
Just get the contents as an array
List<String[]> list = new ArrayList<>();
...
String[][] array = list.toArray(new String[0][0]); // the size here is not important, the array is just an indication of the type to use
You can use .toArray(T[]) for this.
public static void main(String[] args) {
List<String[]> l = new ArrayList<String[]>();
String[] a = {"lala", "lolo"};
String[] b = {"lili", "lulu"};
l.add(a);
l.add(b);
String[][] r = new String[l.size()][];
r = l.toArray(r);
for(String[] s : r){
System.out.println(Arrays.toString(s));
}
}
Output:
[lala, lolo]
[lili, lulu]

Multiple type array

I am working with an array and need some help. I would like to create an array where the first field is a String type and the second field is an Integer type.
For result:
Console out
a 1
b 2
c 3
An array can only have a single type.
You can create a new class like:
Class Foo{
String f1;
Integer f2;
}
Foo[] array=new Foo[10];
You might also be interested in using a map (it seems to me like you're trying to map strings to ids).
EDIT:
You could also define your array of type Object but that's something i'd usually avoid.
You could create an array of type object and then when you print to the console you invoke the toString() of each element.
Object[] obj = new Object[]{"a", 1, "b", 2, "c", 3};
for (int i = 0; i < obj.length; i++)
{
System.out.print(obj[i].toString() + " ");
}
Will yield:
a 1 b 2 c 3
Object[] randArray = new Object [3];
randArray[0] = new Integer(5);
randArray[1] = "Five";
randArray[2] = new Double(5.0);
for(Object obj : randArray) {
System.out.println(obj.toString());
}
Is this what you're looking for?
Object[] myArray = new Object[]{"a", 1, "b", 2 ,"c" , 3};
for (Object element : myArray) {
System.out.println(element);
}
Object [] field = new Object[6];
field[0] = "a";
field[1] = 1;
field[2] = "b";
field[3] = 2;
field[4] = "c";
field[5] = 3;
for (Object o: field)
System.out.print(o);
try using Vector instead of Array.

Convert lines to different Arrays in Java

I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex:
1 line - A,B,C
2 line - D,E,F,G, etc.
and convert this to:
[A,B,C]
[D,E,F,G]
I'm doing this with String.split(", ")
ArrayList<String> al_1 = new ArrayList<String>();
ArrayList<String> al_2 = new ArrayList<String>();
while(true){
String[] line = rbuff.readLine().split(",");
for(String i : line){
al_1.add(i);
}
if(line == null) break;
}
What's the best way to fill the second?
Thx.
Maybe you must use
ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>();
instead of
ArrayList<String> al_1 = new ArrayList<String>();
ArrayList<String> al_2 = new ArrayList<String>();
and fullfill this list with al.add()
IMO easier to keep a list of lists.
List<List<String>> lineLists = new ArrayList<List<String>>();
while (true) {
List<String> lineList = new ArrayList<String>();
String[] line = rbuff.readLine().split(",");
for (String i : line) {
lineList.add(i);
}
lineLists.add(lineList);
if (line == null) break;
}
(Ignoring that there are any number of ways to split immediately into an array or list w/o the inner loop. Either way, the inner loop should be refactored.)
This solution will allow you to add a new ArrayList to the myArrayList for each row your read of your file:
List<List<String>> myArrayList = new ArrayList<List<String>>();
List<String> myStrings;
while (true) {
myStrings = new ArrayList<String>();
String[] line = rbuff.readLine().split(",");
for (String i : line) {
myStrings.add(i);
}
myArrayList.add(myStrings);
if (line == null)
break;
}
You will have a List with one List inside for each row of your text file.
MyArrayList
|
|_____List('A', 'B', 'C')
|
|_____List('D', 'E', 'F', 'G')
|
|_____(...)
Well that's pretty much what I'd do, but with the mention that if you don't need your lines to inside ArrayList objects, you can use array Strings (String[]). Here's an example:
private static String s1 = "A,B,C",s2="D,E,F";
private static List<String> lines = new ArrayList<String>(){{add(s1);add(s2);}};
public static void main(String[] args) throws Throwable {
Map<Integer,String[]> linesToArraysMap = new HashMap<Integer,String[]>();
for(int i=1;i<=lines.size();i++) {
linesToArraysMap.put(i, lines.get(i-1).split(","));
//if you want to get them as ArrayLists you can do:
//List<String> lineList = Arrays.asList(lines.get(i-1).split(","));
}
for(String[] stringArr:linesToArraysMap.values()) {
System.out.println(Arrays.toString(stringArr));
}
}

Categories

Resources