java8 第五章-----集合

目录

 5.1、Collection接口

5.2、List接口

 5.3、Set接口

5.4、Map接口

5.5、Collections类


集合遍历方式可以查看我之前写的文章:

集合遍历(19条消息) Collection----集合四种遍历方式_Xiayebuliang的博客-CSDN博客_collection 遍历的方式

 5.1、Collection接口

常见方法:

三种遍历:

Collection<String> collection = new ArrayList<>();
collection.add("张三");
collection.add("李四");
collection.add("王五");

//第一种:使用迭代器
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
    String s = iterator.next();
    System.out.println(s);
}

//第二种:使用增强for,其实是迭代器的升级版
for (String s : collection) {
    System.out.println(s);
}

//第三种:使用forEach,其实是增强for的升级版
collection.forEach(s -> {
    System.out.println(s);
});

 遍历删除:

Collection<String> collection = new ArrayList<>();
collection.add("aaa");
collection.add("bbb");
collection.add("ccc");
collection.add("ddd");
//使用迭代器删除
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
    String next = iterator.next();
    if (next.equals("aaa")) {
        iterator.remove();
    }
}
collection.forEach(System.out::println);

流式操作:

Stream流是由三部分组成的。数据源,零个或一个或多个中间操作,零个或一个终止操作。

在 Java 8 中,集合接口有两个方法来生成流:

  • stream() − 为集合创建串行流。
  • parallelStream() − 为集合创建并行流。

和以前的Collection操作不同,Stream操作还有两个基础的特征:

  • Pipelining :中间操作都会返回流对象本身。这样多个操作可以串联成一个管道,如同流式风格(fluent style)。这样做可以对操作进行优化,比如延迟执行(laziness)和短路( short-circuiting)。
  • 内部迭代 :以前对集合遍历都是通过Iterator或者For-Each的方式,显式的在集合外部进行迭代,这叫做外部迭代。Stream提供了内部迭代的方式,通过访问者模式(Visitor)实现。
     

 注意:Stream操作并不会存储元素,而是按需计算。

中间操作:

filter:过滤操作

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);

 distinct:去重操作

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream().distinct().forEach(System.out::println);

limit:返回前 n 个元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream().limit(5).forEach(System.out::println);

skip:跳过前 n 个元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream().skip(5).forEach(System.out::println);

sorted:对流进行排序

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream().sorted().forEach(System.out::println);

map:将每个元素映射为新元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream().map(s -> s.toUpperCase()).forEach(System.out::println);

flatMap:将每个流转化为一个流

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.stream()
        .map(s -> s.toLowerCase())
        .peek(s -> System.out.println("toLowerCase value: " + s))
        .map(s -> s.toUpperCase())
        .peek(s -> System.out.println("toUpperCase value: " + s))
        .forEach(System.out::println);

max:常用于获取流中最大值

Collection<Integer> collection = Arrays.asList(3, 2, 1, 4, 5, 6);
Optional<Integer> max = collection.stream().max(Comparator.comparingInt(o -> o));
max.ifPresent(System.out::println);

min:常用于获取流中最小值

Collection<Integer> collection = Arrays.asList(3, 2, 1, 4, 5, 6);
Optional<Integer> max = collection.stream().min(Comparator.comparingInt(o -> o));
max.ifPresent(System.out::println);

终止操作:

forEach:用于串行流保持顺序遍历

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.parallelStream().forEach(System.out::println);

forEachOrdered:用于并行流保持顺序遍历

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
collection.parallelStream().forEachOrdered(System.out::println);

anyMatch:检查是否至少匹配一个元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
boolean result = collection.parallelStream().anyMatch(s -> s.equals("aaa"));
System.out.println(result);

noneMatch:检查是否没有匹配所有元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
boolean result = collection.parallelStream().noneMatch(s -> s.equals("aaa"));
System.out.println(result);

allMatch:检查是否匹配所有元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
boolean result = collection.parallelStream().allMatch(s -> s.equals("aaa"));
System.out.println(result);

findAny:将返回当前流中的任意元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
Optional<String> any = collection.parallelStream().findAny();
if (any.isPresent()) {
    System.out.println(any.get());
}

findFirst:将返回当前流中的第一元素

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
Optional<String> first = collection.parallelStream().findFirst();
if (first.isPresent()) {
    System.out.println(first.get());
}

count:返回当前流中元素的总数

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
long count = collection.parallelStream().count();
System.out.println(count);

reduce:对流中的数据进行计算

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
Optional<String> reduce = collection.parallelStream().reduce((acc, item) -> acc + item);
if (reduce.isPresent()) {
    System.out.println(reduce.get());
}
String string = collection.parallelStream().reduce("prefix_", (acc, item) -> acc + item);
System.out.println(string);

collect:对流中的数据进行收集

Collection<String> collection = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
ArrayList<String> collect1 = collection.parallelStream().collect(Collectors.toCollection(ArrayList<String>::new));
LinkedList<String> collect2 = collection.parallelStream().collect(Collectors.toCollection(LinkedList<String>::new));
List<String> collect3 = collection.parallelStream().collect(Collectors.toList());
Set<String> collect4 = collection.parallelStream().collect(Collectors.toSet());
Map<String, String> collect5 = collection.parallelStream().collect(Collectors.toMap(k -> k, v -> v, (oldVale, newValue) -> newValue));
String string = collection.parallelStream().collect(Collectors.joining());

5.2、List接口

常见方法:

三种遍历:

List<String> list = Arrays.asList("abc", "abd", "abe", "123", "456", "789", "aaa", "bbb", "ccc", "aaa");
ListIterator<String> listIterator = list.listIterator();

//第一种:使用下标遍历
for (int i = 0; i < list.size(); i++) {
    String s = list.get(i);
    System.out.println(i + "=" + s);
}

//第二种:从前向后遍历
while (listIterator.hasNext()) {
    int nextIndex = listIterator.nextIndex();
    String next = listIterator.next();
    System.out.println(nextIndex + "=" + next);
}

//第三种:从后向前遍历
while (listIterator.hasPrevious()) {
    int previousIndex = listIterator.previousIndex();
    String previous = listIterator.previous();
    System.out.println(previousIndex + "=" + previous);
}

遍历删除:

List<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
//使用迭代器删除
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
    String next = listIterator.next();
    if (next.equals("bbb")) {
        listIterator.remove();
    }
}
//使用迭代器删除
while (listIterator.hasPrevious()) {
    String previous = listIterator.previous();
    if (previous.equals("ccc")) {
        listIterator.remove();
    }
}
list.forEach(System.out::println);

子类对比:

相同点:元素的存取是有序的,可以重复,可以存取null,元素有下标

不同点:

 5.3、Set接口

子类对比:

相同点:元素的存取是无序的,不能重复,可以存取null,元素无下标

不同点:

5.4、Map接口

常见方法:

 三种遍历:

Map<Integer, String> map = new HashMap<>();
map.put(1, "张三");
map.put(2, "李四");
map.put(3, "王五");
map.put(4, "赵六");

//第一种遍历:遍历所有键值对
Set<Map.Entry<Integer, String>> entries = map.entrySet();
entries.forEach((Map.Entry<Integer, String> entry) -> {
    System.out.println(entry.getKey() + "=" + entry.getValue());
});

//第二种遍历:遍历所有键集合
Set<Integer> keySets = map.keySet();
keySets.forEach((key) -> {
    System.out.println(key);
});

//第三种遍历:遍历所有值集合
Collection<String> values = map.values();
values.forEach((value) -> {
    System.out.println(value);
});

遍历删除:

Map<Integer, String> map = new HashMap<>();
map.put(1, "张三");
map.put(2, "李四");
map.put(3, "王五");
map.put(4, "赵六");

//第一种删除
Set<Map.Entry<Integer, String>> entries = map.entrySet();
Iterator<Map.Entry<Integer, String>> entryIterator = entries.iterator();
while (entryIterator.hasNext()) {
    Map.Entry<Integer, String> next = entryIterator.next();
    if (next.getKey() == 2) {
        entryIterator.remove();
    }
}

//第二种删除
Set<Integer> keySets = map.keySet();
Iterator<Integer> keySetIterator = keySets.iterator();
while (keySetIterator.hasNext()) {
    Integer next = keySetIterator.next();
    if (next == 3) {
        keySetIterator.remove();
    }
}

子类对比:

相同点:以键值对的形式添加元素,键不能重复,值可以重复

不同点:

5.5、Collections类

常见方法:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: LinkedList是Java集合类之一,是一个双向链表。它特有的方法包括: 1. addFirst(E e):将指定元素插入此列表的开头。 2. addLast(E e):将指定元素插入此列表的结尾。 3. getFirst():返回此列表的第一个元素。 4. getLast():返回此列表的最后一个元素。 5. removeFirst():移除并返回此列表的第一个元素。 6. removeLast():移除并返回此列表的最后一个元素。 7. offerFirst(E e):在此列表的开头插入指定的元素。 8. offerLast(E e):在此列表的结尾插入指定的元素。 9. pollFirst():获取并移除此列表的第一个元素,如果此列表为空,则返回 null。 10. pollLast():获取并移除此列表的最后一个元素,如果此列表为空,则返回 null。 ### 回答2: List是Java集合类中常用的一种,而LinkedList是List集合中的一种实现,和ArrayList相比,它具有一些独特的方法。 首先,LinkedList支持在list开头和结尾添加元素的方法。即addFirst(E e)和addLast(E e)。这两个方法在其他List实现中是没有的。这对于链表来说非常方便,因为在链表中,添加元素时只需要修改指针的指向即可,而不用像数组一样需要移动其他元素。 其次,LinkedList支持获取链表的头部和尾部元素的方法。即getFirst()和getLast()。同样,其他List实现中也没有这种方法,这也是LinkedList适合做队列和栈这种数据类型的原因之一。 除了这些独有的方法之外,LinkedList还具有一些其他List实现也有的方法。例如remove(int index)和size()方法就是常规List接口所具有的。LinkedList还实现了Queue和Deque接口,使得LinkedList也可以充当队列和双端队列。 需要注意的一点是,由于LinkedList是链表的形式,所以访问其中的元素时速度比较慢。因此,在需要随机访问元素的情况下,最好使用ArrayList。但是,当需要频繁在开头和结尾添加或删除元素时,LinkedList则具有明显的优势。 总之,LinkedList是List集合中的一种实现,它具有一些独特的方法,如addFirst,getFirst等方法。同时,它也可以作为队列、栈、双端队列等数据结构的实现。但是在需要随机访问元素的情况下,建议使用其他List实现,如ArrayList。 ### 回答3: Java集合类是Java编程中常用的工具之一,List是其中一种很重要的集合类。LinkedList是List的一种实现方式,LinkedList在插入和删除数据方面比较快。本文将会介绍LinkedList的特有方法的使用。 LinkedList继承了AbstractSequentialList,也实现了List、Deque、Cloneable、Serializable接口。由于LinkedList的底层实现是双向链表,因此它具有插入和删除元素效率高的特点。 下面是LinkedList特有的方法: 1. public void addFirst(E e),将指定元素添加到此列表的开头: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.addFirst("C++"); System.out.println(linkedList); // [C++, Java, Python] 2. public void addLast(E e),将指定元素添加到此列表的结尾: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.addLast("C++"); System.out.println(linkedList); // [Java, Python, C++] 3. public E removeFirst(),删除并返回此列表的第一个元素: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); String first = linkedList.removeFirst(); System.out.println(first); // Java System.out.println(linkedList); // [Python, C++] 4. public E removeLast(),删除并返回此列表的最后一个元素: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); String last = linkedList.removeLast(); System.out.println(last); // C++ System.out.println(linkedList); // [Java, Python] 5. public E getFirst(),返回此列表的第一个元素: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); String first = linkedList.getFirst(); System.out.println(first); // Java 6. public E getLast(),返回此列表的最后一个元素: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); String last = linkedList.getLast(); System.out.println(last); // C++ 7. public E peekFirst(),获取但不移除此列表的第一个元素: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); String first = linkedList.peekFirst(); System.out.println(first); // Java System.out.println(linkedList); // [Java, Python, C++] 8. public E peekLast(),获取但不移除此列表的最后一个元素: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); String last = linkedList.peekLast(); System.out.println(last); // C++ System.out.println(linkedList); // [Java, Python, C++] 9. public boolean offerFirst(E e),将指定元素插入此列表的开头: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); boolean result = linkedList.offerFirst("C++"); System.out.println(result); // true System.out.println(linkedList); // [C++, Java, Python] 10. public boolean offerLast(E e),将指定元素插入此列表的结尾: LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); linkedList.add("Python"); boolean result = linkedList.offerLast("C++"); System.out.println(result); // true System.out.println(linkedList); // [Java, Python, C++] LinkedList是一个非常实用的Java集合类,我们可以根据自己的需求选择使用其中的特有方法。在实际开发中,结合List可以方便地实现队列和栈的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值