Home  >  Article  >  Java  >  What factory methods have been added for collections in Java 9?

What factory methods have been added for collections in Java 9?

PHPz
PHPzforward
2023-08-21 08:37:02912browse

Java 9中为集合添加了哪些工厂方法?

Factory method is a special type of static method that can be used to create unmodifiable collection instances . This means that we can use these methods to create lists, sets and maps containing a small number of elements.

List.of()

List.of() is a static factory method that provides a convenient way to create immutableList.

Syntax

<strong>List.of(elements...)</strong>

Example

import java.util.List;
public class ListTest {
   public static void main(String[] args) {
      <strong>List<String></strong> list =<strong> List.of</strong>("item 1", "item 2", "item 3", "item 4", "item 5");
      for(String l : list) {
         System.out.println(l);
      }
   }
}

Output

<strong>item 1
item 2
item 3
item 4
item 5</strong>

##Set.of() method

Set.of() is a static factory method that provides a convenient way to create immutable sets.

Syntax

<strong>Set.of(elements...)
</strong>

Example

import java.util.Set;
public class SetTest {
   public static void main(String[] args) {
      <strong>Set<String></strong> set = <strong>Set.of</strong>("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
      for(String s : set) {
         System.out.println(s);
      }
   }
}

Output

<strong>Item 5
Item 1
Item 2
Item 3
Item 4</strong>

##Map.of() and Map. ofEntries() method

The

Map.of()

and Map.ofEntries() are static factory methods that provide a convenient way to create Immutable Mapping. Syntax

<strong>Map.of(k1, v1, k2, v2)
Map.ofEntries(entry(k1, v1), entry(k2, v2),...)</strong>

Example

import java.util.Map;
public class MapTest {
   public static void main(String[] args) {
      <strong>Map<Integer, String></strong> map = <strong>Map.of</strong>(101, "Raja", 102, "Adithya", 103, "Jai");
      for(<strong>Map.Entry<Integer, String></strong> m : map.<strong>entrySet()</strong>) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}

Output

<strong>103 Jai
102 Adithya
101 Raja</strong>

The above is the detailed content of What factory methods have been added for collections in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete