📜  Java将数组转换为集合

📅  最后修改于: 2022-05-13 01:55:34.690000             🧑  作者: Mango

Java将数组转换为集合

Java Collection提供了一种架构来存储和操作对象组。数据的数据类型可以更改为通用数据类型,如数组到集合中。基于数组的数据转换为 基于集合我们可以使用Java。实用程序。数组。该类提供了一个静态方法 asList(T... a) 将数组转换为 收藏

脚步:

  • 定义一个函数来编写逻辑
  • 从用户获取数组输入
  • 借助asList()函数将数组输入转换为Collection

使用的方法:

1. asList(): Java.util.Arrays类的这个方法用于返回一个由指定数组支持的固定大小的列表,作为基于数组和基于集合的API之间的桥梁,结合Collection.toArray ()。

这在 O(1) 时间内运行。

示例 1:

Java
// Convert an Array into Collection in Java
  
// import java util library
import java.util.*;
  
// class for writing logic of the problem
public class ArrayToCollection {
    public static void main(String args[])
    {
        // array input
        String playersArray[]
            = { "Virat", "Sachin", "Rohit", "Bumrah" };
        
        // printing input elements for comparision
        System.out.println("Array input: "
                           + Arrays.toString(playersArray));
        
        // converting array into Collection
        // with asList() function
        List playersList = Arrays.asList(playersArray);
        
        // print converted elements
        System.out.println("Converted elements: "
                           + playersList);
    }
}


Java
// Convert an Array into Collection in Java
  
// import java util library
import java.util.*;
  
public class ArrayToCollection {
    
    public static void main(String args[])
    {
        String countryArray[]
            = { "India", "Pakistan", "Afganistan",
                "Srilanka" };
        
        System.out.println("Array input: "
                           + Arrays.toString(countryArray));
  
        List countryList = Arrays.asList(countryArray);
        System.out.println("Converted elements: "
                           + countryList);
    }
}


输出:

Array input: [Virat, Sachin, Rohit, Bumrah]
Converted elements: [Virat, Sachin, Rohit, Bumrah]

示例 2:

Java

// Convert an Array into Collection in Java
  
// import java util library
import java.util.*;
  
public class ArrayToCollection {
    
    public static void main(String args[])
    {
        String countryArray[]
            = { "India", "Pakistan", "Afganistan",
                "Srilanka" };
        
        System.out.println("Array input: "
                           + Arrays.toString(countryArray));
  
        List countryList = Arrays.asList(countryArray);
        System.out.println("Converted elements: "
                           + countryList);
    }
}

输出:

Array input: [India, Pakistan, Afganistan, Srilanka]
Converted elements: [India, Pakistan, Afganistan, Srilanka]