方式一:利用Java流(Steam)实现(List,Map适用)

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {

	public static void main(String[] args) {
		Integer[] arr = {1,2,3,3};
		
		Set<Integer> set = Arrays.stream(arr).collect(Collectors.toSet());//适用于JDK>=1.8
		
		for (Integer integer : set) {
			System.out.println(integer);//【输出:1,2,3】
		}

	}

}

方式二:for-each方法

import java.util.HashSet;
import java.util.Set;

public class Main {

	public static void main(String[] args) {
		String[] numbers = new String[] { "One", "Two", "Three", "One", "Six" };

		Set<String> set = new HashSet<>();

		for (String str : numbers) {
			set.add(str);

		}
	}
}

方式三:"Collections.addAll()"方法

String[] num = new String[] { "One", "Two", "Three", "One", "Six" };

Set<String> set=new HashSet<>();

Collections.addAll(set,num);

System.out.println(set);//输出【[Six, One, Two, Three]】

方法四:"Arrays.asList()"方法(array⇒list⇒set)

String[] num = new String[] { "One", "Two", "Three", "One", "Six" };

Set<String> set = new HashSet<>(Arrays.asList(num));//不推荐,大小固定不能增删

System.out.println(set);
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐