Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a list to another list in java

here is my 2 lists and i want to append the values of list books to book2 for correcting the output

  List<Book>books=null;
  List<Book> books2=null;
  String searchParam=null;
  searchParam=txtSearch.getText();

  if(category.isSelected()){

    List<Category> categorys =null; 

    categorys=ServiceFactory.getCategoryServiceImpl().findAllByName(searchParam);

    for(Category i:categorys){                          
    books=ServiceFactory.getBookServiceImpl().findAllBookByCategoryId(i.getId());
    System.out.println(i.getName()+books+"hi..");

here append or add list to another

    if(books!=null){
    books2=books.add(books2);
    }
    }
    }

    for(Book book:books){
    txtSearchResult.append(book.getName()+"\n");
    }

error shows

The method add(Book) in the type List<Book> is not applicable for the arguments (List<Book>)

if u know the answer please share here..

like image 604
Prasanth A R Avatar asked Feb 16 '14 01:02

Prasanth A R


People also ask

Can I append a list to a list Java?

It is possible to add all elements from one Java List into another List . You do so using the List addAll() method.

How do you add a list to a different list?

Use the extend() Method to Append a List Into Another List in Python. Python has a built-in method for lists named extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.

How do I create a list from one list to another in Java?

Create a list of the class objects from an array using the asList method. Create an empty list. Loop through each element of the original list, and invoke the SerializationUtils. clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list.


1 Answers

When programming in Java, you should be referencing the Javadoc for the class or interface you're using to answer these sorts of questions.

You would use:

books2.addAll(books);

to append all entries in books to books2.

From the Javadoc linked above:

boolean addAll(Collection<? extends E> c)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)

like image 91
Brian Roach Avatar answered Oct 02 '22 15:10

Brian Roach