0

i have one method which accept List<?> i want to two list i want to add two list in single generic list but i am unable to add i tried to create one generic type list but its not accepting.

I tried this:

List<Object> list = new ArrayList<>();
list.add(model.getfirstlist().getItems());                      
list.add(model.getSecondlist().getItems());
setListData(list)

My function is:

public void setListData(List<?> list) {
       // print list
}

getItems have field same field id, title

setListData(model.getfirstlist().getItems()) // working fine

My function is like

public void setListData(List<?> list) {
       // print list
}

I am trying to add two list in single list and pass it into

singlelist = ( model.getfirstlist().getItems() +
model.getSecondlist().getItems())
setListData(singlelist);

Please suggest me how i will do this.

2
  • You want the addAll method of List. Commented Mar 28, 2019 at 15:12
  • yes @VGR we have two list with same type Commented Mar 28, 2019 at 15:13

2 Answers 2

1

Use the addAll method of Collection and List:

List<Item> list = new ArrayList<>();
list.addAll(model.getfirstlist().getItems());                      
list.addAll(model.getSecondlist().getItems());
setListData(list);
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a List that would contain as elements both lists:

e.g.

List<Integer> listA = Arrays.asList(1,2,3,4,5);
List<Integer> listB = Arrays.asList(6,7,8,9);

List<List<Integer>> lists = Arrays.asList(listA, listB);

Then using streams api you could flatten the list you have created try the following:

List<Object> flattenList = Stream.of(lists)
                                 .flatMap(x -> x.stream())
                                 .collect(Collectors.toList());

If you can't use stream api you can try the following approach:

List<Integer> listA = Arrays.asList(1,2,3,4,5);
List<Integer> listB = Arrays.asList(6,7,8,9);

listA.addAll(listB);

Now listA would contain also the items of listB.

8 Comments

Thanks for answer let me try your answer.
we can not use Stream API there is some version issue with stream API do you have any other solution .
@MARSH What version of Java you use ? Stream API has been inserted in Java 8.
I am using java 8 but when i use this Android then there is some SDK version issue is coming we cant go with Stream API
we have not integer type we have Item type object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.