Java9中对集合类扩展的of方法解析

网友投稿 325 2022-12-12

Java9中对集合类扩展的of方法解析

目录java9 集合类扩展of方法Java9集合类中重载多个of方法原因有如下描述

Java9 集合类扩展of方法

package com.jd.collections;

import org.junit.Test;

import java.util.List;

import java.util.Map;

import java.util.Optional;

import java.util.Sethttp://;

import java.util.stream.IntStream;

import java.util.stream.Stream;

public class StreamTest {

@Test

public void testSet() {

Set integerSet = Set.of(1, 2, 3, 4, 5, 6, 7, 8);

System.out.println(integerSet);

}

@Test

public void testList() {

List integerSet = List.of(1, 2, 3, 4, 5, 6, 7, 8);

System.out.println(integerSet);

}

@Test

public void testMap() {

Map stringMap = Map.of("k1", "v1", "k2", "v2", "k3", "v3");

System.out.println(stringMap);

Map.Entry entry1 = Map.entry("k1", "v1");

Map.Entry entry2 = Map.entry("k11", "v11");

Map.Entry entry3 = Map.entry("k12", "v12");

Map mapOfEntries = Map.ofEntries(entry1, entry2, entry3);

System.out.println(mapOfEntries);

}

@Test

public void testStream1() {

Optional integerOptional = Stream.ofNullable(Integer.valueOf("1232")).findAny();

System.out.println(integerOptional.get());

}

@Test

public void testStream2() {

Stream.of(1, 2, 3, 4, 5, 6).dropWhile(x -> x == 6)/*.takeWhile(x -> x == 2)*/.forEach(System.out::println);

}

@Test

public void testStream3() {

IntStream.of(1, 2, 3, 4, 5, 6).forEach(System.out::println);

}

@Test

public void testStream4() {

IntStream.iterate(1, i -> i < 10, i -> i + 2).forEach(System.out::println);

}

// @Test

// public void testFlow() {

// Flow.Processor

// }

}

Java9集合类中重载多个of方法原因

在java9 api的集合类中,有很多看似一样的重载of方法:

那这里有个问题是为什么有了VarArgs(可变长参数)方法,还需要定义那么多重载的方法呢?查看官方的更新日志中可以发现

有如下描述

http://openjdk.java.net/jeps/269

These will include varargs overloads, so that there is no fixed limit on the collection size. However, the collection instances so created may be tuned for smaller sizes. Special-case APIs (fixed-argument overloads) for up to ten of elements will be provided. While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls. Significantly, the source code of the call site is the same regardless of whether a fixed-arg or varargs overload is called.

大致得意思是,虽然重载了这么多of方法会造成api的混乱,但它避免了varargs调用引起的数组分配,初始化和垃圾收集开销。因为固定参数的重载方法,返回的是一个immutable list(不可变集合)。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:intellij idea 2021.2 打包并上传运行spring boot项目的详细过程(spring boot 2.5.4)
下一篇:Kotlin lateinit与by lazy案例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~