如何将数组转换为Set

在本节中,我们将向展示如何将字符串数组转换为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] 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264143.html

(0)
上一篇 2022年6月7日
下一篇 2022年6月7日

相关推荐

发表回复

登录后才能评论