我想在java中合并3个arraylist。有谁知道哪种方法最好?
使用ArrayList.addAll()
。这样的东西应该工作(假设列表包含String
对象;你应该相应地改变)。
List<String> combined = new ArrayList<String>();
combined.addAll(firstArrayList);
combined.addAll(secondArrayList);
combined.addAll(thirdArrayList);
我可以通过您的评论看到您实际上可能正在尝试创建2D列表。如果是这样,以下代码应该起作用:
List<List<String>> combined2d = new ArrayList<List<String>>();
combined2d.add(firstArrayList);
combined2d.add(secondArrayList);
combined2d.add(thirdArrayList);
使用java.util.Arrays.asList来简化合并怎么样?
List<String> one = Arrays.asList("one","two","three");
List<String> two = Arrays.asList("four","five","six");
List<String> three = Arrays.asList("seven","eight","nine");
List<List<String>> merged = Arrays.asList(one, two, three);
使用Java 8 Streams:
清单清单
List<List<String>> listOfList = Stream.of(list1, list2, list3).collect(Collectors.toList());
字符串列表
List<String> list = Stream.of(list1, list2, list3).flatMap(Collection::stream).collect(Collectors.toList());
使用Java 9 List.of静态工厂方法(警告:此列表是不可变的,不允许为null)
List<List<String>> = List.of(list1, list2, list3);
list1, list2, list3
的类型为List<String>
好吧差不多一年了我知道但我最近遇到了这个问题,我有一个对象(JobList),它包含一个对象列表(作业)这个列表可以是任何大小我的解决方案需要X个JobLists并返回一个JobList,所以给出3个JobList对象,它将返回一个Job对象列表,如下所示
job1FromJobList1 job1FromJobList2 job1FromJobList3 job2FromJobList1 job2FromJobList2 job2FromJobList3 job3FromJobList1 job3FromJobList2 job3FromJobList3
这就是我的意思,如果我说合并,你可以忽略我创建对象的部分主要部分获得最大,然后将它们添加到列表,如果我<jobList.getJobList()。size()
public JobList merge(List<JobList> jobListList) {
JobList mergedJobList = new JobList();
int max = 0;
ArrayList<Job> mergedList = new ArrayList<>();
ArrayList<String> tags = new ArrayList<>();
for (JobList jobList : jobListList){
max = Math.max(max,ListConverter.jobListFromString(jobList.getJobList()).size());
for (String tag : jobList.getJobListsTags()){
tags.add(tag);
}
}
for (int i = 0; i < max; i++){
for (JobList jobList : jobListList){
if (i < ListConverter.jobListFromString(jobList.getJobList()).size())
mergedList.add(ListConverter.jobListFromString(jobList.getJobList()).get(i));
}
}
mergedJobList.setJobListTitle("Title");
mergedJobList.setJobListFavourite(false);
mergedJobList.setJobListsTags((String[]) tags.toArray());
mergedJobList.setJobListColour(this.getString(R.string.white));
mergedJobList.setJobList(ListConverter.stringFromJobList(mergedList));
return mergedJobList;
}