logo

Initialiser une liste en Java

Le Java.util.Liste est une interface enfant de Collection . Il s'agit d'une collection ordonnée d'objets dans laquelle des valeurs en double peuvent être stockées. Puisque List préserve l’ordre d’insertion, il permet l’accès positionnel et l’insertion d’éléments. L'interface de liste est implémentée par Liste des tableaux , Liste liée , Vecteur et Empiler Des classes.

listeinterfacejava



List est une interface et les instances de List peuvent être créées des manières suivantes :

 List a = new ArrayList(); List b = new LinkedList(); List c = new Vector(); List d = new Stack();>

Vous trouverez ci-dessous les méthodes suivantes pour initialiser une liste :

  1. Utilisation de la méthode List.add()

    Puisque list est une interface, on ne peut pas l’instancier directement. Cependant, on peut créer des objets des classes qui ont implémenté cette interface et les instancier.



    Peu de classes qui ont implémenté l'interface List sont Pile, ArrayList, LinkedList, vecteur etc.

    Syntaxe:

     List list=new ArrayList(); List llist=new LinkedList(); List stack=new Stack();>

    Exemples:






    import> java.util.*;> import> java.util.function.Supplier;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// For ArrayList> >List list =>new> ArrayList();> >list.add(>1>);> >list.add(>3>);> >System.out.println(>'ArrayList : '> + list.toString());> > >// For LinkedList> >List llist =>new> LinkedList();> >llist.add(>2>);> >llist.add(>4>);> >System.out.println(>'LinkedList : '> + llist.toString());> > >// For Stack> >List stack =>new> Stack();> >stack.add(>3>);> >stack.add(>1>);> >System.out.println(>'Stack : '> + stack.toString());> >}> }>

    >

    >

    Sortir:

     ArrayList : [1, 3] LinkedList : [2, 4] Stack : [3, 1]>

    Initialisation à double accolade peut également être utilisé pour effectuer le travail ci-dessus.

    Syntaxe:

     List list=new ArrayList(){{ add(1); add(2); add(3); }};>

    Exemples:




    import> java.util.*;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// For ArrayList> >List list =>new> ArrayList() {{> >add(>1>);> >add(>3>);> >} };> >System.out.println(>'ArrayList : '> + list.toString());> > >// For LinkedList> >List llist =>new> LinkedList() {{> >add(>2>);> >add(>4>);> >} };> >System.out.println(>'LinkedList : '> + llist.toString());> > >// For Stack> >List stack =>new> Stack() {{> >add(>3>);> >add(>1>);> >} };> >System.out.println(>'Stack : '> + stack.toString());> >}> }>

    >

    >

    Sortir:

     ArrayList : [1, 3] LinkedList : [2, 4] Stack : [3, 1]>
  2. Utilisation de Arrays.asList()

    • Création d'une liste immuable

      Tableaux.asList() crée une liste immuable à partir d'un tableau. Il peut donc être utilisé pour instancier une liste avec un tableau.

      Syntaxe:

      List list=Arrays.asList(1, 2, 3);>

      Exemples:




      import> java.util.Arrays;> import> java.util.List;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Instantiating List using Arrays.asList()> >List list = Arrays.asList(>1>,>2>,>3>);> > >// Print the list> >System.out.println(>'List : '> + list.toString());> >}> }>

      >

      >

      Sortir:

       List : [1, 2, 3]>
    • Création d'une liste mutable

      Syntaxe:

      List list=new ArrayList(Arrays.asList(1, 2, 3));>

      Exemples:




      import> java.util.ArrayList;> import> java.util.Arrays;> import> java.util.List;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Creating a mutable list using Arrays.asList()> >List list =>new> ArrayList(> >Arrays.asList(>1>,>2>,>3>));> > >// Print the list> >System.out.println(>'List : '> + list.toString());> > >list.add(>5>);> > >// Print the list> >System.out.println(>'Modified list : '> + list.toString());> >}> }>

      arbre binaire de traversée par correspondance

      >

      >

      Sortir:

       List : [1, 2, 3] Modified list : [1, 2, 3, 5]>
  3. Utiliser les méthodes de la classe Collections

    Il existe différentes méthodes dans la classe Collections qui peuvent être utilisées pour instancier une liste. Ils sont:

    1. Utilisation de Collections.addAll()

      Collections la classe a une méthode statique tout ajouter() qui peut être utilisé pour initialiser une liste. Collections.addAll() prendre n'importe quel nombre d'éléments après avoir été spécifié avec la collection dans laquelle les éléments doivent être insérés.

      Syntaxe:

      List list = Collections.EMPTY_LIST; Collections.addAll(list = new ArrayList(), 1, 2, 3, 4);>

      Exemples:




      import> java.util.*;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Create an empty list> >List list =>new> ArrayList();> > >// Instantiating list using Collections.addAll()> >Collections.addAll(list,>1>,>2>,>3>,>4>);> > >// Print the list> >System.out.println(>'List : '> + list.toString());> >}> }>

      >

      >

      Sortir:

       List : [1, 2, 3, 4]>
    2. Utilisation de Collections.unmodifiableList()

      Collections.unmodifiableList() renvoie une liste qui ne peut pas être modifiée, c'est-à-dire qu'elle ne peut ni ajouter ni supprimer un élément. Toute tentative de modification de la liste entraînera un UnsupportedOperationExample.

      Syntaxe:

      List list = Collections .unmodifiableList(Arrays.asList(1, 2, 3));>

      Exemple 1:




      import> java.util.*;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Creating the list> >List list = Collections.unmodifiableList(> >Arrays.asList(>1>,>2>,>3>));> > >// Print the list> >System.out.println(>'List : '> + list.toString());> >}> }>

      >

      >

      Sortir:

       List : [1, 2, 3]>

      Exemple 2 :




      import> java.util.*;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >try> {> >// Creating the list> >List list = Collections.unmodifiableList(> >Arrays.asList(>1>,>2>,>3>));> > >// Print the list> >System.out.println(>'List : '> + list.toString());> > >// Trying to modify the list> >System.out.println(>'Trying to modify the list'>);> >list.set(>0>, list.get(>0>));> >}> > >catch> (Exception e) {> >System.out.println(>'Exception : '> + e);> >}> >}> }>

      >

      >

      Sortir:

       List : [1, 2, 3] Trying to modify the list Exception : java.lang.UnsupportedOperationException>
    3. Utilisation de Collections.singletonList()

      Collections.singletonList() renvoie une liste immuable composée d'un seul élément.

      Syntaxe:

      List list = Collections.singletonList(2);>

      Exemple 1:




      import> java.util.*;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Creating the list> >List list = Collections.singletonList(>2>);> > >// Print the list> >System.out.println(>'List : '> + list.toString());> >}> }>

      >

      >

      Sortir:

       List : [2]>
  4. Utilisation du flux Java 8

    Avec l'introduction de Stream et de la programmation fonctionnelle dans Java 8, on peut désormais construire n'importe quel flux d'objets, puis les collecter sous forme de liste.

    Syntaxe:

     1. List list = Stream.of(1, 2, 3) .collect(Collectors.toList()); 2. List list = Stream.of(1, 2, 3) .collect(Collectors.toCollection(ArrayList::new)); 3. List list = Stream.of(1, 2, 3, 4) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));>

    Exemples:




    import> java.util.*;> import> java.util.stream.Collectors;> import> java.util.stream.Stream;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Creating a List using Syntax 1> >List list1 = Stream.of(>1>,>2>,>3>)> >.collect(Collectors.toList());> > >// Printing the list> >System.out.println(>'List using Syntax 1: '> >+ list1.toString());> > >// Creating a List using Syntax 2> >List list2 = Stream> >.of(>3>,>2>,>1>)> >.collect(> >Collectors> >.toCollection(ArrayList::>new>));> > >// Printing the list> >System.out.println(>'List using Syntax 2: '> >+ list2.toString());> > >// Creating a List using Syntax 3> >List list3 = Stream> >.of(>1>,>2>,>3>,>4>)> >.collect(> >Collectors> >.collectingAndThen(> >Collectors.toList(),> >Collections::unmodifiableList));> > >// Printing the list> >System.out.println(>'List using Syntax 3: '> >+ list3.toString());> >}> }>

    >

    >

    Sortir:

     List using Syntax 1: [1, 2, 3] List using Syntax 2: [3, 2, 1] List using Syntax 3: [1, 2, 3, 4]>
  5. Utilisation de Java 9 List.of()

    Java 9 a introduit la méthode List.of() qui prend en compte un nombre illimité d'arguments et en construit une liste compacte et non modifiable.

    Syntaxe:

    List unmodifiableList = List.of(1, 2, 3);>

    Exemples:




    import> java.util.List;> > public> class> GFG {> >public> static> void> main(String args[])> >{> > >// Creating a list using List.of()> >List unmodifiableList = List.of(>1>,>2>,>3>);> > >// Printing the List> >System.out.println(>'List : '> >+ unmodifiableList.toString());> >}> }>

    >

    >

    SORTIR:

     [1, 2, 3]>