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

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

PHPz
Release: 2023-08-21 08:37:02
forward
938 people have browsed it

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>
Copy after login

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);
      }
   }
}
Copy after login

Output

<strong>item 1
item 2
item 3
item 4
item 5</strong>
Copy after login

##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>
Copy after login

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);
      }
   }
}
Copy after login

Output

<strong>Item 5
Item 1
Item 2
Item 3
Item 4</strong>
Copy after login

##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>
Copy after login

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());
      }
   }
}
Copy after login

Output

<strong>103 Jai
102 Adithya
101 Raja</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template