I do have this code, and I would like to print out all the array's values of Arraylist.
thanks for your help in advanced.
here is my code:
for (int i = 0; i <count; i++) {
System.out.println("list #" + i);
for (int j = 0; j < list[i].size(); j++) {
list[i].get(j);
System.out.println("elements of array in arraylist "+list[i].get(j));
}
}
For printing elements of an array stored in arraylist,you will have to to do the following:
for each element of arraylist
get array from arraylist
for each array element in array
print array element.
You seemed to be iterating array of List type instead.
Edit your code with further detail on your data structure
for (Object[] array : list)
for (Object o : array)
System.out.println("item: " + o);
See if this can work for you. I think it's simpler:
int numLists = 10; // Or whatever number you need it to be.
ArrayList [] arrayOfLists = new ArrayList[numLists];
// you realize, of course, that you have to create and add those lists to the array.
for (ArrayList list : arrayOfLists) {
System.out.println(list);
}
I'd wonder why you don't prefer a List of Lists:
List<List<String>> listOfLists = new ArrayList<List<String>>();
// add some lists of Strings
for (List<String> list : listOfLists) {
System.out.println(list);
}
Below code works fine for me
public class Solution
{
public static void main(String[] args)
{
int T,N,i,j,k=0,Element_to_be_added_to_the_array;
Scanner sn=new Scanner(System.in);
T=sn.nextInt();
ArrayList<Integer>[] arr=new ArrayList[T];
for(i=0;i<T;i++)
{
arr[k]=new ArrayList<Integer>();
N=sn.nextInt();
for(j=0;j<N;j++)
{
Element_to_be_added_to_the_array=sn.nextInt();
arr[k].add(Element_to_be_added_to_the_array);
}
k++;
}
//Printing elements of all the arrays contained within an arraylist
for(i=0;i<T;i++)
{
System.out.println("array["+i+"]");
for(j=0;j<arr[i].size();j++)
{
System.out.println(arr[i].get(j));
}
}
}
}
Related
I have 2 lists one for the sentence one for the keywords. The idea is to check if the sentence have the keywords. and put them in a list for each sentence in order.
I am sorry if this is already duplicated here in advance.
List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
My idea was to create 2 nested loops for each list:
for (int b = 0; b < sentence.size(); b++) {
for (int c = 0; c < keyword.size(); c++) {
if (sentence.get(b).contains(keyword.get(c))) {
System.out.println(keyword.get(c));
}
}
}
The output of this is:
dog
good
this
cats
milk
beautiful
are
The desired output would be:
[this,good,dog]
[cats,milk]
[are,beautiful]
So it is like getting all the existing keywords, in the order of the sentence,not related to keywords order.
and then group the existing keywords for each sentence, as in the order of existence.
Hope it is clear. Would really appreciate any ideas. doesnt have to follow the same method.
Iterate over your sentence list. For each sentence iterate over your keyword list. Add each found keyword found in a tempList, sort the tempList by the index of keyword in sentence and finally add each tempList to a list of lists. Example:
public static void main(String[] args) {
List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
List<List<String>> result = new LinkedList<>();
for(String sen: sentence){
List<String> tempList = new ArrayList<>();
for(String key: keyword){
if(sen.contains(key)){
tempList.add(key);
}
}
tempList.sort(new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return sen.indexOf(o1) - sen.indexOf(o2) ;
}
});
result.add(tempList);
}
for(List<String> r : result){
System.out.println(r);
}
}
You need a slight modification in your looping
for (int i = 0; i < sentence.size(); i++) {
String[] matchArray = new String[sentence.get(i).split(" ").length];
for (int j = 0; j < keyword.size(); j++) {
if (sentence.get(i).contains(keyword.get(j))) {
matchArray[Arrays.asList(sentence.get(i).split(" ")).indexOf(keyword.get(j))] = keyword.get(j);
}
}
List<String> matchList = new ArrayList<String>();
for(String match: matchArray) {
if(match != null) {
matchList.add(match);
}
}
System.out.println(matchList);
}
For every sentence create an array with size same as the sentence (just to ensure size). Now when matches are found get the index of the match from sentence and add element to that particular index of the array. So at the end of keyword iteration you will have all matches in array with null values if some words are not matching.
Now declare a new List of String into which add the elements from array which are not null. At last print the list.
I think Map would be a good choice here. Just make sentences keys for the map and keywords as value. Following is the code for the same.
Map <String, ArrayList<String>> sentences= new HashMap<>();
sentences.put("this is a good dog", new ArrayList<>());
sentences.put("cats drink milk", new ArrayList<>());
sentences.put("Animals are beautiful creatures", new ArrayList<>());
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
keyword.forEach(word -> sentences.entrySet().stream()
.filter(map -> map.getKey().contains(word)).
forEach(map -> sentences.computeIfAbsent(map.getKey(), key->new ArrayList<>()).add(word)));
sentences.forEach((key, value) -> System.out.println(value));
Try something like this:
for (String sen: sentence) {
System.out.print("[");
boolean first = true;
for (String word: sen.split("[\\s\\p{Punct}]")) {
if (keyword.contains(word)) {
if (first) {
first = false;
} else {
System.out.print(",");
}
System.out.print(word);
}
}
System.out.println("]");
}
this should do it, printing exactly in the format you requested :
for (int b = 0; b < sentence.size(); b++) {
String arr[] = sentence.get(b).split("\\s+");
List result = new ArrayList<>();
for (int c = 0; c < arr.length; c++ ) {
if (keyword.contains(arr[c]))
result.add(arr[c]);
}
System.out.println(result);
}
I would use the following :
for(String currentSentence : sentence) {
List<String> keywordsInSentence = new ArrayList<>();
for (String word : currentSentence.split("\\s+")) {
if (keyword.contains(word)) {
keywordsInSentence.add(word);
}
}
System.out.println(keywordsInSentence);
}
You can try it here.
(and I'd rename sentence into sentences or sentenceList and similarly for keyword, otherwise it's just confusing)
If you need to do anything more to the keywords than immediately displaying them, you could insert the keywordsInSentence lists into a Map<String, List<String>> you would value by replacing the System.out.println by map.put(currentSentence, keywordsInSentence).
I want to display the contents of an array of linked lists. Each linked list contains a String array. The content of the array of linked lists is displaying as [[[Ljava.lang.String;#15db9742], [[Ljava.lang.String;#6d06d69c], [[Ljava.lang.String;#7852e922]]. How do I solve this?
public class LinkedListOfStringArrays {
public static void main(String[] args) {
LinkedList<String[]> Values[] = new LinkedList[3];
for (int i = 0; i < 3; i++){
Values[i] = new LinkedList<String[]>();
}
String[] first = {"first element", "ABC"};
String[] second = {"second element", "DEF"};
String[] third = {"third element", "GHI"};
Values[0].add(first);
Values[1].add(second);
Values[2].add(third);
System.out.println(Arrays.toString(Values));
}
}
You will have to loop through the lists and output it manually:
// Loop through the Array of LinkedLists
for(LinkedList<String[]> list : Values) {
// Next loop through each of the lists
for(String[] keyValuePair : list) {
// Then output the values as you see fit
System.out.println(keyValuePair[0] + " - " + keyValuePair[1]);
}
}
This will give you the following output:
first element - ABC
second element - DEF
third element - GHI
In Java 8 you can try as
Stream.of(Values).
flatMap(list -> list.stream()).
forEach(values -> System.out.println(String.join("-",values)));
I have an arraylist in which
ArrayList<ArrayList<String>> listofItems=new ArrayList<ArrayList<String>>();
in the list of items I have items like this
[[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22]]
how to iterate and store in another array these values split into two like
[1,2,3,4,5,6,7,8,9,10,11] and [11,12,13,14,15,16,17,18,19,20,21,22]. I have used advanced for loop
for(ArrayList<String> list:listofItems)
{
for (String s:list)
{
//I dont know how to add logic here.
}
}
I am assuming here that both lists will also hold string type data.If you want Integer type,you can parse while adding.
ArrayList<ArrayList<String>> listofItems = new ArrayList<ArrayList<String>>();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
for (ArrayList<String> list : listofItems) {
for (String s : list) {
// there shud be some condition how much elements you want in a
// list or some condition
// to decide in which list we need to add item
if (list.size() < 12)
list1.add(s);
else
list2.add(s);
}
}
Use something like that:
if (yourlist.size()>0) {
List<String> first = yourList.subList(0, (int)Math.ceil(yourlist.size()/2.0));
List<String> second = yourList.subList((int)Math.ceil(yourlist.size()/2.0), yourlist.size());
}
Would be separate your list in 2 lists divided in the half.
You can use this code to store your list into another list.
List<String> stringList = new ArrayList<String>();
for(ArrayList<String> list:listofItems) {
for (String s:list) {
stringList.add(s);
}
}
In this case, when you add info to listOfItems, you should try example like this
for(int i = 0; i< 2; i++){
for(int j = 0; j < n; j++){
/// add util break n
lists.get(i).add(strTemp);
}
}
You can change i < 2 into any number you want. I only make this sample for you.
I have a simple class that takes out items that were already in another array from the first array, by putting it into a list. Whenever I run this program though, another program that I created starts to run. I have tried to change the run configuration as well, but it doesn't show up on the list..? Here is the code:
package collections;
import java.util.*;
public class Arraystring {
public static void main(String [ ] args, int Collection, int String){
String[] things = { "eggs", "lasers", "hats", "pie" };
List<String> list1 = new ArrayList<String>();
for (String x : things){ //enhanced for loop
list1.add(x);
}
System.out.println(list1);
String[] thingstwo = { "lasers", "hats" };
List<String> list2 = new ArrayList<String>();
for(int i = 0;i<list2.size(); /* size for list, length for array */ i++) //regular for loop
{
list2.add(thingstwo[i]);
}
//print list one
for(int i = 0;i<list1.size(); /* size for list, length for array */ i++) //regular for loop
{
System.out.println(list1.get(i)); //Use .get for lists instead of []
}
editlist(list1, list2);
System.out.println();
//print list one
for(int i = 0;i<list1.size(); /* size for list, length for array */ i++) //regular for loop
{
System.out.println(list1.get(i)); //Use .get for lists instead of []
}
}
public static void editlist(Collection<String> l1, Collection<String> l2){
Iterator<String> it = l1.iterator(); //Goes through each list item by item
while (it.hasNext()){
if(l2.contains(it.next())){
it.remove();
}
System.out.println(it);
}
}
}
Thanks for helping, I really appreciate it.
You can execute Run file command from menu/shortcut or change main project in the IDE.
Specify yours IDE and proper shortcuts/commands would be given to you.
Upd.
You have error in yours logic:
String[] thingstwo = {"lasers", "hats"};
List<String> list2 = new ArrayList<>();
for (int i = 0; i < list2.size(); i++)
list2.add(thingstwo[i]);
Look at it line-by-line:
String[] thingstwo = {"lasers", "hats"};
Defining array, ok.
List<String> list2 = new ArrayList<>();
Defining list of strings, ok.
for (int i = 0; i < list2.size(); i++)
Looping throug items of list list2, not ok. list2 at this point is empty. Assuming you wanted to loop through thingstwo and add it's items to list2, so fixing the code:
for (int i = 0; i < thingstwo.length; i++)
And...
list2.add(thingstwo[i]);
Adding i-th item of thingstwo to list2, ok.
Running:
[eggs, lasers, hats, pie]
eggs
lasers
hats
pie
eggs
pie
I have the following ArrayList...
ArrayList<ArrayList<Integer>> row1 = new ArrayList<ArrayList<Integer>>();
The following arraylists are added to it....
row1.add(cell1);
row1.add(cell2);
row1.add(cell3);
row1.add(cell4);
row1.add(totalStockCell);
I want to iterate through the arraylist row1 and print the contents.
Would a loop within a loop work here?
E.g.
while(it.hasNext()) {
//loop on entire list of arraylists
while(it2.hasNext) {
//each cell print values in list
} }
This is the canonical way you do it:
for(List<Integer> innerList : row1) {
for(Integer number : innerList) {
System.out.println(number);
}
}
for (ArrayList<Integer> list : row1)
{
for (Integer num : list)
{
//doSomething
}
}
Java enhanced-for loops use an iterator behind the scenes.
If you want to use Iterator, nested loops will work:
Iterator<ArrayList<Integer>> it = row1.iterator();
while(it1.hasNext())
{
Iterator<Integer> itr = it.next().iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
Here some functional approach:
ArrayList<ArrayList<Integer>> row1 = new ArrayList<>();
row1.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
row1.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
row1.stream().flatMap(Collection::stream).forEach(System.out::println);
Old question, but I am just curious why no one has mentioned this way,
for(int i=0; i<list.size(); i++) {
for(int j=0; j<list.get(i).size(); j++) {
System.out.print(list.get(i).get(j) + " ");
}
System.out.println();
}
This is same as accessing a matrix in 2D arrays.