Pin It

How to add or group one collection into another collection in Java ?.

Program to demonstrate how to add or group one collection into another collection in Java

package com.hubberspot.example;

//1. We have to import three Collections
//framework class and interface as 
//ArrayList, Collections and Collection

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;


public class GroupCollectionsDemo {

 public static void main(String[] args) {

  // 2. Creating a Collection reference variable
  // for holding the objects. Collection is interface
  // which is the base interface for all the collections
  // such as ArrayList, Queue etc. Here we have created 
  // an ArrayList object which is holding the Integer objects
  // and its object is been referenced by Collection 
  Collection<Integer> list = new ArrayList<Integer>();

  // 3. Adding six Integer objects to Collection
  list.add(1);
  list.add(2);
  list.add(3);
  list.add(4);
  list.add(5);
  list.add(6);

  // 4. Creating yet another array collection and adding six 
  //Integer objects to it
  Integer[] array = new Integer[6];
  array[0] = 7;
  array[1] = 8;
  array[2] = 9;
  array[3] = 10;
  array[4] = 11;
  array[5] = 12;

  // 5. Looping each Collection object and printing it on 
  // console
  System.out.println("Elements in Collection before adding :");
  for(Integer i : list) {
   System.out.print(i + " ");
  }
  System.out.println("\n");

  // 6. Using Collections class addAll() method to add array of
  // Integers to the list Collection 
  Collections.addAll(list, array);

  System.out.println("Elements in Collection after adding :");

  // 7. Looping each Collection object after adding 
  // Integer array to it and printing it on 
  // console
  for(Integer i : list) {
   System.out.print(i + " ");
  }
  System.out.println("\n");

  // 8. Using Collections class addAll() method to add some
  // more integers to it after adding an array of
  // Integers to the list Collection
  Collections.addAll(list, 13,14,15,16,17,18);


  // 9. Looping each Collection object after adding 
  // Integer array to it plus some more integers 
  // to it and printing it on 
  // console

  System.out.println("Elements in Collection after adding more elements :");
  for(Integer i : list) {
   System.out.print(i + " ");
  }
 }
}



Output of the program :



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot