在本节中,我们将向展示如何将字符串数组转换为Set。可以通过以下方法使用实现:
- For-each循环
- Arrays.asList()方法(array⇒list⇒set)
- Collections.addAll()方法
文件:ArrayToSetExample.java -
package com.yiibai.tutorial;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* @author yiibai
*
*/
public class ArrayToSetExample {
public static void main(String[] args) {
/* Array to be converted */
String[] numbers=new String[]{"One""Two""Three""One""Six"};
/* Method - 1 */
Set<String> numberList1=new HashSet<>();
for (String integer : numbers) {
numberList1.add(integer);
}
System.out.println("Number List1="+numberList1);
/* Method - 2 */
Set<String> numberList2=new HashSet<>(Arrays.asList(numbers));
System.out.println("Number List2="+numberList2);
/* Method - 3 */
Set<String> numberList3=new HashSet<>();
Collections.addAll(numberList3 numbers);
System.out.println("Number List3="+numberList3);
}
}
执行得到以下结果 -
Number List1=[Six One Two Three]
Number List2=[Six One Two Three]
Number List3=[Six One Two Three]