怀旧网个人博客网站地址:怀旧网,博客详情:Java Set 集合介绍
Set 系列集合简介
回顾 Collection 接口方法
可以参考前面发布的 Collection 介绍博客:网页链接
Set 接口常用方法演示
实例化方法
Set<String> set = new HashSet<>();
- 因为 Set 作为接口的方式存在,所以这边是采用实现了 Set 接口的 HashSet 来进行实例化的。
add 方法测试
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("张三");
set.add("张三");
System.out.println(set);
}
- 这边的输出结果只有一个张三,原因是因为 Set 的特性,里面不可以存在重复元素的.
public static void main(String[] args) {
Set<String> set = new HashSet<>();
boolean b1 = set.add("张三");
boolean b2 = set.add("张三");
System.out.println(b1);
System.out.println(b2);
}
- 在 Set 集合中我们的add方法的返回值是有作用的,不想 ArrayList 那样直接就返回true了,在 Set 中是通过添加元素进行是否成功来作为返回值的结果,我们这边第一次添加张三进入集合,集合原数据中没有张三所以添加成功,返回true,在第二次在添加张三这个元素的时候,已经有了张三这个元素,所以添加失败返回false。
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("张三");
set.add("李四");
set.add("王五");
System.out.println(set);
}
- 通过这边的输出也可以看出来当前的存储顺序和实际的输出顺序是不一样的,证明了 Set 的无序性。
- 另外因为 Set 是没有顺序的存储的,所以也就没有对应的get方法了。
remove 方法
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("张三");
set.add("李四");
set.add("王五");
boolean b1 = set.remove("张三");
boolean b2 = set.remove("张三");
System.out.println(b1);
System.out.println(b2);
}
- remove方法和有序集合的区别就是,不能够通过索引的方式来进行元素删除(还是因为 Set 是无序的列表)。
Set 集合的遍历
迭代器对象遍历
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("张三");
set.add("李四");
set.add("王五");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()){
String data = iterator.next();
System.out.println(data);
}
}
增强 for 循环遍历
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("张三");
set.add("李四");
set.add("王五");
for (String s : set) {
System.out.println(s);
}
}
lambda 表达式遍历
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("张三");
set.add("李四");
set.add("王五");
set.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.print(s + "\t\t");
}
});
System.out.println("\n----------------------");
set.forEach(s ->System.out.print(s + "\t\t"));
System.out.println("\n----------------------");
set.forEach(System.out::println);
}