My arraylist contains String array objects.
How Can I get all values?
My code is below,
String cordinates1c,cordinates2l,cordinates2m;
String[] array1={cordinates1c,cordinates2l,cordinates2m};
String[] array2={cordinates1c,cordinates2l,cordinates2m};
ArrayList alist=new ArrayList();
alist.add(array1);
alist.add(array2);
//retreieving
for(int i=0;i<alist.size();i++)
System.out.println("arrayList="+alist.get(i));
if I try to retrieve like above it gives,
07-12 12:42:09.977: INFO/System.out(743): arrayList=[[Ljava.lang.String;#43e11b28]
How to do that?
Arrays should be printed with the help of Arrays.toString() or Arrays.deepToString().
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws Exception {
String[][] a = {{"a", "b", "c"}, {"d", "e"}};
System.out.println(Arrays.deepToString(a));
}
}
for(int i=0;i<alist.size();i++) {
for (String a : alist.get(i)) {
System.out.println(a);
}
}
You have to iterate over the array of strings, too.
You can iterate over your List and then use Arrays.toString() or Arrays.deepToString() to print array contents
for (String[] eachArray : alist) {
System.out.println("arrayList=" + Arrays.deepToString(eachArray));
}
ArrayList<String[]> l;
for (String[] a : l) {
for (String s : a) {
System.out.println(s);
}
}
Hoping that you are trying to print the string in array1
ArrayList<String> alist= (ArrayList<String>) Arrays.asList(array1);
Now print the data from alist.
also have a look into alist.addAll(collection)
But following snippet will add array1 and array2 object to your ArrayList, So retrieval you will get an array object
alist.add(array1);
alist.add(array2);
Are you looking for something like this ?
String cordinates1c = "1", cordinates2l = "2", cordinates2m = "3";
String[] array1 = {cordinates1c, cordinates2l, cordinates2m};
String[] array2 = {cordinates1c, cordinates2l, cordinates2m};
List<String []> alist=new ArrayList<String []>();
alist.add(array1);
alist.add(array2);
for (String[] strings : alist) {
System.out.println(StringUtils.join(strings));
}
Output:
123
123
Related
I have an ArrayList which contains several String[]. I want to loop through the ArrayList and group the inner String[] that contain a matching value. In this case, I'm looking specifically at the second value in the String[] (ex. "CompanyA").
I'm having difficulty understanding what the best logical pattern for this is and how it might be implemented. Any help is greatly appreciated.
List<String[]> attArrayList = new ArrayList<String[]>();
String[] entry1 = { "EventOne", "CompanyA", "Matthew" };
String[] entry2= { "EventOne", "CompanyA", "Mary" };
String[] entry3 = { "EventOne", "CompanyB", "Bates" };
String[] entry4 = { "EventOne", "CompanyC", "Carson" };
attArrayList.add(entry1);
attArrayList.add(entry2);
attArrayList.add(entry3);
attArrayList.add(entry4);
for (int i = 0; i < attArrayList.size(); i++) {
// ...
}
My desired result is something like this:
[[EventOne, CompanyA, Matthew], [EventOne, CompanyA, Mary]], [EventOne, CompanyB, Bates], [EventOne, CompanyC, Carson]
Map<String, ArrayList<String[]>> map = new TreeMap<>();
for (String[] strs : attArrayList) {
if (!map.containsKey(strs[1])) {
ArrayList<String[]> list = new ArrayList<>();
list.add(strs);
map.put(strs[1], list);
} else {
map.get(strs[1]).add(strs);
map.put(strs[1], map.get(strs[1]));
}
}
for (String[] strs : map.get("CompanyA")) {
System.out.println(Arrays.toString(strs));
}
You can try this.I think it`s easier to understand than using stream(though stream has less code).
You could use groupingBy to group the items based on the second column:
Map<String, List<String[]>> groups = attArrayList.stream()
.collect(groupingBy(arr -> arr[2]));
How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.
This programm shuffles a source list by pairs. So that original list
"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"
trasfoms to
11^12 19^20 17^18 15^16 1^2 5^6 3^4 13^14 7^8 9^10
The above is true while commented line is uncommented. Now, if line A is commented then all the elements in shuffleList are 19^20.
public class ShuffleService {
public static void shuffleList(List<String> list) {
System.out.println(list);
ArrayList<String[]> shuffleList = new ArrayList<String[]>(10);
String[] arr = new String[2];
boolean flag = false;
int step = 0;
for(String s: list){
if(flag){
arr[1]=s;
} else {
arr[0]=s;
}
flag=!flag;
step++;
if(step==2){
shuffleList.add(arr);
step=0;
//arr = new String[2]; //**line A**
}
}
Collections.shuffle(shuffleList);
for(String[] val: shuffleList){
System.out.print(val[0]);
System.out.print("^");
System.out.println(val[1]);
}
}
public static void main(String[] args) {
String[] a = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"};
List<String> list1 = Arrays.asList(a);
shuffleList(list1);
}
}
So why do I need to uncomment line A in the program to work properly?
Because when you rewrite the values to arr (without remaking it), you're also going to modify the values already in the list.
Adding an object to the list doesn't stop you from modifying it, it will not make copies on its own. By calling new String[2] in your loop you're effectively building a new string array for each pair that you add to the list, which is what you want.
List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
Basically I want an array of {a, b, c} however this isn't working. Do I have to iterate and load each element instead? How would I do this?
My error output looks like this:
[Ljava.lang.String;#3d4b7453
[Ljava.lang.String;#24c21495
Your code works fine, but it looks like you're printing the wrong thing. Do this instead:
for (String[] strs : list) {
System.out.println(Arrays.toString(strs));
}
Printing just an array will give you output like what you're seeing.
Try
List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
System.out.println(Arrays.toString(list.get(0)));
I think you want to print this way: -
List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
System.out.println(Arrays.toString(list.get(0)));
This prints: - [a, b, c]
You could use Arrays.toString() to print elements of an array,
System.out.println(Arrays.toString(list.get(0)));
or alternatively iterate over them:
for(String s : list.get(0)) System.out.println(s);
You can use Arrays.asList()
List<String> list = new ArrayList<String>();
String str = "a b c";
list.addAll(Arrays.asList(str.split(" ")));
To print the result is like:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
I have a list like this:
List<MyObject[]> list= new LinkedList<MyObject[]>();
and on Object like this:
MyObject[][] myMatrix;
How can I assign the "list" to "myMatrix"?
I don't want to loop over the list and assign element by element to MyMatrix, but I want to assign it directly (with the oppurtune modifications) if possible.
Thanks
You could use toArray(T[]).
import java.util.*;
public class Test{
public static void main(String[] a){
List<String[]> list=new ArrayList<String[]>();
String[][] matrix=new String[list.size()][];
matrix=list.toArray(matrix);
}
}
Javadoc
The following snippet shows a solution:
// create a linked list
List<String[]> arrays = new LinkedList<String[]>();
// add some trivial test data (note: arrays with different lengths)
arrays.add(new String[]{"a", "b", "c"});
arrays.add(new String[]{"d", "e", "f", "g"});
// convert the datastructure to a 2D array
String[][] matrix = arrays.toArray(new String[0][]);
// test output of the 2D array
for (String[] s:matrix)
System.out.println(Arrays.toString(s));
Try it on ideone
Let us assume that we have a list of 'int' array.
List<int[]> list = new ArrayList();
Now to convert it into 2D array of type 'int', we use 'toArray()' method.
int result[][] = list.toArray(new int[list.size()][]);
We can generalize it further like-
List<T[]> list = new ArrayList();
T result[][] = list.toArray(new T[list.size()][]);
Here, T is the type of array.
Use toArray() or toArray(T[]) method of LinkedList.
You can do it like this:
public static void main(String[] args) {
List<Item[]> itemLists = new ArrayList<Item[]>();
itemLists.add(new Item[] {new Item("foo"), new Item("bar")});
itemLists.add(new Item[] {new Item("f"), new Item("o"), new Item("o")});
Item[][] itemMatrix = itemLists.toArray(new Item[0][0]);
for (int i = 0; i < itemMatrix.length; i++)
System.out.println(Arrays.toString(itemMatrix[i]));
}
Output is
[Item [name=foo], Item [name=bar]]
[Item [name=f], Item [name=o], Item [name=o]]
assuming that Item is as follows:
public class Item {
private String name;
public Item(String name) {
super();
this.name = name;
}
#Override
public String toString() {
return "Item [name=" + name + "]";
}
}
Converto list to array using. List.Array()
Then Use System.arraycopy to copy to the 2d array works well for me
Object[][] destination = new Object[source.size()][];
System.arraycopy(source, 0, destination, 0, source.size());