JDK8提供了非常多的便捷用法和语法糖,其编码效率几乎接近于C#开发,maven则是java目前为止最赞的jar包管理和build工具,这两部分内容都不算多,就合并到一起了。

愿编写java代码的过程如:Fast & Furious

鸟枪换炮咯,走起!J Java 7发布于2011年,Java 8发布于2014年,Java 9还远么?

在javase8中,lambda表达式的形式基本好C#中一致,Stream和LINQ类似,Future<T>和Task<T>类似,可以这样说,javase8大体达到了C#编码的便捷程度哈!帅帅哒

  • Lambda(和.NET一样)

功能

示例

函数式接口

Arrays.sort(words, (first, second) ->

Integer.compare(first.length(), second.length()));

BiFunction<String, String, Integer> comp =

(first, second) -> Integer.compare(first.length(), second.length());

常见的函数式接口(推荐使用),和C#Action<T>,Function<T, R>类似

Runnable,Supplier<T>,Consumer<T>, Function<T, R>, Predicate<T>

方法引用

Arrays.sort(words, String::compareToIgnoreCase);

构造器引用

list.stream().collect(Collectors.toList());

默认方法,接口中的静态方法

不太推荐

概念

所有的lambda表达式都符合闭包,且是延迟执行的

  • Stream

功能

示例

创建Stream

Stream<String> song = Stream.of("Shanghai", "Beijing");

filter,map,flatmap方法

分别对应C#中Linq的where,select和selectMany

常见操作

去除重复: .distince()

排序.sorted(), 反向.reversed()

聚合方法 .max(), findFirst(), .findAny(), .anyMatch()

聚合操作 .reduce((x,y)->x+y)

分组和分片: .groupingBy(), mapping(), joining()

并行流: .parallel()

Optional类型

Optional<T>是对T类型封装,它不会返回null,使得引用更安全

  • 时间日期

在1.8以前,主要使用joda-time库来处理一些比较复杂的时间日期操作,现在有官方的api了。

功能

示例

时间线Instant

Instant start = Instant.now();

Thread.sleep(1000);

Instant end = Instant.now();

Duration timeElapsed = Duration.between(start, end);

long millis = timeElapsed.toMillis();

本地日期LocalDate

LocalDate today = LocalDate.now();

LocalDate oneDay = LocalDate.of(2017, 7, 9);

LocalDate addDay = LocalDate.now().plusDays(10);

日期校正器TemporalAdjueters

获取2017年5月的第一个周二

LocalDate time = LocalDate.of(2017, 5, 1)

.with(TemporalAdjusters.nextOrSame(DayOfWeek.TUESDAY));

本地时间LocalTime

LocalTime time = LocalTime.of(16, 37, 11);

带时区的时间ZonedDateTime

ZonedDateTime applloTime = ZonedDateTime.of(2017, 5, 9, 16, 40, 11, 0, ZoneId.of("America/New_York"));

格式化和解析DateTimeFormatter

用于替代过去的DateFormat,SimpleDateFormat

遗留代码的互操作

Instant start = Instant.now();其他类型的操作类似

Date oldDate = Date.from(start);

  • 并发

功能

示例

原子值

AtomicLong nextNumber = new AtomicLong();

nextNumber.incrementAndGet();

ConcurrentHashMap的改进

ConcurrentMap<String, Integer> map = new ConcurrentHashMap();

map.putIfAbsent("age", 100);

map.compute("name", (k, v) -> v == null ? 1 : v + 1);

map.merge("age", 1, (oldValue, newValue) -> oldValue + newValue);

批量数据操作:reduceValue, reduceKeys

并行数组操作

String[] people = new String[]{"xionger", "shuaishuaida"};

Arrays.parallelSort(people);

Future,和.NET的Task<T>类似

CompletableFuture<String> contents =

CompletableFuture.supplyAsync(() -> getAsync());

这部分知识之后再加强

  • 杂项

功能

示例

字符串

String joined = String.join("/", "user", "local", "bin");

数字扩展

Long testValue = Integer.toUnsignedLong(Integer.MAX_VALUE);

新的数值函数

int result = Math.floorMod(Math.toIntExact(100L), 3);

新增集合方法

list.forEach((item) -> System.out.println(item));

Map: remove, putIfAbsent, computeIf, merge

排序:Arrays.sort(people, Comparator.comparing(Person::getAge));

使用文件

这儿看到try-with-resource,等价于using,java代码也可以和.net一样简介

try (Stream<String> lines = Files.lines(path)) {

Optional<String> pwd = lines.filter(s -> s.contains("pwd")).findFirst();}

Base64编码

Base64.Encoder encoder = Base64.getMimeEncoder();

try (OutputStream output = Files.newOutputStream(encoderPath)) {

Files.copy(originalPath, encoder.wrap(output));}

注解

通过在注解上添加@Repeatable,使得注解可多次使用

可以使用基于类型的注解

private @NonNull List<String> names = new ArrayList<>();

方法参数反射,可以反射获取参数的名称

Java7

使用Path接口来代替File类

Path absolute = Paths.get("/", "home", "shanghai ");

Files.write(absolute, content.getBytes(StandardCharsets.UTF_8));

Tip: demo项目

Maven使用起来相对比较简单,其配置均写在setting.xml中,主要的配置项包括镜像的选择和本地仓库的选择,如下所示。

 <?xml version="1.0" encoding="UTF-8"?>
 <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 <localRepository>E:\javaAssist\maven\repository</localRepository>
 <pluginGroups>
 </pluginGroups>
 <proxies>
 </proxies>
 </servers>
 <mirrors>
 <!-- 阿里云仓库 -->
 <mirror>
 <id>alimaven</id>
 <mirrorOf>central</mirrorOf>
 <name>aliyun maven</name>
 <url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
 </mirror>
 <!-- 中央仓库1 -->
 <mirror>
 <id>repo1</id>
 <mirrorOf>central</mirrorOf>
 <name>Human Readable Name for this Mirror.</name>
 <url>http://repo1.maven.org/maven2/</url>
 </mirror>
 <!-- 中央仓库2 -->
 <mirror>
 <id>repo2</id>
 <mirrorOf>central</mirrorOf>
 <name>Human Readable Name for this Mirror.</name>
 <url>http://repo2.maven.org/maven2/</url>
 </mirror>
 </mirrors>
 <profiles>
 </profiles>
 </settings>

其他常见的包括Eclipse中maven的配置,这部分只需要指定好Installations和UserSetting就好。

Maven编译的常见命令如下所示

命令 诠释
mvn package 生成target目录,编译、测试代码,生成测试报告,生成jar/war文件 
mvn tomcat:run 运行项目于tomcat[jetty等server也OK]上
mvn compile  编译
mvn test   编译并测试
mvn clean 清空生成的文件 
mvn install -X 想要查看完整的依赖踪迹,包含那些因为冲突或者其它原因而被拒绝引入的构件,打开 Maven 的调试标记运行 
Maven的Scope  
compile 编译范围,默认的范围
provided 已提供范围,比如有些web相关jar,tomcat中有,但本地没有时使用
runtime 运行时范围,比如编译时只需要slf4j-api,运行时才需要具体的实现jar
test 测试范围,例如junit,spring-test

Maven示例

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.bjorktech.cayman</groupId>
     <artifactId>cm-web</artifactId>
     <packaging>war</packaging>

     <parent>
         <artifactId>cayman</artifactId>
         <groupId>com.bjorktech</groupId>
         <version>1.0.0-SNAPSHOT</version>
     </parent>

     <properties>
         <!-- Web -->
         <jsp.version>2.3.1</jsp.version>
         <jstl.version>1.2</jstl.version>
         <servlet.version>3.1.0</servlet.version>
         <!-- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> -->
     </properties>

     <dependencies>
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-webmvc</artifactId>
         </dependency>
         <!-- <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId>
             <version>7.0</version> <scope>provided</scope> </dependency> -->
         <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>jstl</artifactId>
             <version>${jstl.version}</version>
         </dependency>
         <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
             <version>${servlet.version}</version>
             <scope>provided</scope>
         </dependency>
         <dependency>
             <groupId>javax.servlet.jsp</groupId>
             <artifactId>javax.servlet.jsp-api</artifactId>
             <version>${jsp.version}</version>
             <scope>provided</scope>
         </dependency>
         <!-- tx -->
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-tx</artifactId>
         </dependency>
         <!-- aop -->
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-aop</artifactId>
         </dependency>
         <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjweaver</artifactId>
         </dependency>
         <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjrt</artifactId>
             <version>1.8.5</version>
         </dependency>
         <!-- mybatis -->
         <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis</artifactId>
         </dependency>
         <dependency>
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>
         </dependency>
         <dependency>
             <groupId>joda-time</groupId>
             <artifactId>joda-time</artifactId>
         </dependency>
         <!-- log -->
         <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-access</artifactId>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-classic</artifactId>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-core</artifactId>
         </dependency>
         <!-- <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId>
             </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId>
             </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId>
             </dependency> -->
         <!-- 本地tomcat -->
         <!-- <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId>
             </dependency> -->
         <!-- json -->
         <dependency>
             <groupId>com.fasterxml.jackson.dataformat</groupId>
             <artifactId>jackson-dataformat-xml</artifactId>
             <version>2.5.3</version>
         </dependency>
         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
             <version>2.5.3</version>
         </dependency>
         <!-- 文件上传 -->
         <dependency>
             <groupId>commons-fileupload</groupId>
             <artifactId>commons-fileupload</artifactId>
             <version>1.3.1</version>
         </dependency>
         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.3</version>
         </dependency>
         <!-- 老式soap -->
         <dependency>
             <groupId>javax.xml.rpc</groupId>
             <artifactId>javax.xml.rpc-api</artifactId>
             <version>1.1.1</version>
         </dependency>
         <dependency>
             <groupId>org.apache.axis</groupId>
             <artifactId>axis</artifactId>
             <version>1.4</version>
         </dependency>
         <!-- axis依赖包 -->
         <dependency>
             <groupId>commons-discovery</groupId>
             <artifactId>commons-discovery</artifactId>
             <version>0.2</version>
             <exclusions>
                 <exclusion>
                     <artifactId>commons-logging</artifactId>
                     <groupId>commons-logging</groupId>
                 </exclusion>
             </exclusions>
         </dependency>
         <dependency>
             <groupId>wsdl4j</groupId>
             <artifactId>wsdl4j</artifactId>
             <version>1.6.3</version>
         </dependency>
         <!-- xml解析 -->
         <dependency>
             <groupId>dom4j</groupId>
             <artifactId>dom4j</artifactId>
             <version>1.6.1</version>
         </dependency>
         <!-- 测试 -->
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-test</artifactId>
         </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
         </dependency>
     </dependencies>
     <build>
         <finalName>cm-web</finalName>
         <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
             </plugin>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-war-plugin</artifactId>
                 <configuration>
                     <!-- 无web.xml不报错 -->
                     <failOnMissingWebXml>false</failOnMissingWebXml>
                 </configuration>
             </plugin>
         </plugins>
     </build>
 </project>

参考资料

  1. Cay, S, Horstmann. 写给大忙人看的JavaSE8[M]. 北京:电子工业出版社, 2015.

像写C#一样编写java代码的更多相关文章

  1. JAVA语言之怎样写出高性能的Java代码?

    本文主要向大家介绍了JAVA语言之怎样写出高性能的 Java 代码?通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助. 在这篇文章中,我们将讨论几个有助于提升Java应用程序性能的方法.我 ...

  2. Jmeter自定义编写Java代码调用socket通信

    一.前言 最近需要测试一款手机游戏的性能,找不到啥录制脚本的工具,然后,另外想办法.性能测试实际上就是对服务器的承载能力的测试,和各种类型的手机客户端没有啥多大关系,手机再好,服务器负载不了,也不能够 ...

  3. 如何更规范化编写Java 代码

    如何更规范化编写Java 代码 Many of the happiest people are those who own the least. But are we really so happy ...

  4. 写了那么多年 Java 代码,终于 debug 到 JVM 了

    继上篇文章 原创 | 全网最新最简单的 openjdk13 代码编译 之后,我们有了自己编译后的 jdk 和 hotspot,如下图所示.接下来就来干一番事情. 搭建调试环境 1.下载 CLion 软 ...

  5. 【原创】怎样才能写出优雅的 Java 代码?这篇文章告诉你答案!

    本文已经收录自 JavaGuide (59k+ Star):[Java学习+面试指南] 一份涵盖大部分Java程序员所需要掌握的核心知识. 本文比较简短,基本就是推荐一些对于写好代码非常有用的文章或者 ...

  6. 如何更规范化的编写JAVA 代码

    如何更规范的编写JAVA代码 一.MyBatis 不要为了多个查询条件而写 1 = 1 当遇到多个查询条件,使用where 1=1 可以很方便的解决我们的问题,但是这样很可能会造成非常大的性能损失, ...

  7. 通过编写Java代码让Jvm崩溃

    在书上看到一个作者提出一个问题"怎样通过编写Java代码让Jvm崩溃",我看了之后也不懂.带着问题查了一下,百度知道里面有这样一个答案: 1 package jvm; 2 3 pu ...

  8. 请阐述调用Activity有哪几种方法,并写出相关的Java代码

    请阐述调用Activity有哪几种方法,并写出相关的Java代码. 答案:可以采用两种方式调用Activity:显示调用和隐式调用.显示调用直接指定了Activity,代码如下: Intent int ...

  9. 【eclipse jar包】在编写java代码时,为方便编程,常常会引用别人已经实现的方法,通常会封装成jar包,我们在编写时,只需引入到Eclipse中即可。

    Eclipse中导入外部jar包 在编写java代码时,为方便编程,常常会引用别人已经实现的方法,通常会封装成jar包,我们在编写时,只需引入到Eclipse中即可. 工具/原料 Eclipse 需要 ...

随机推荐

  1. JS中有关对象的继承以及实例化、浅拷贝深拷贝的奥秘

    一.属性的归属问题 JS对象中定义的属性和方法如果不是挂在原型链上的方法和属性(直接通过如类似x的方式进行定义)都只是在该对象上,对原型链上的没有影响.对于所有实例共用的方法可直接定义在原型链上这样实 ...

  2. Sublime 常用快捷键

    Ctrl+Shift+P:打开命令面板 Ctrl+P:搜索项目中的文件 Ctrl+G:跳转到第几行 Ctrl+W:关闭当前打开文件 Ctrl+Shift+W:关闭所有打开文件 Ctrl+Shift+V ...

  3. 机器学习:Python实现lms中的学习率的退火算法

    ''' 算法:lms学习率的退火算法 解决的问题:学习率不变化,收敛速度较慢的情况 思路:由初始解和控制参数初值开始,对当前解重复进行"产生新解-->计算目标函数差--> 接受或 ...

  4. 数据库CAST()函数和CONVERT()函数比较

    对简单类型转换,CAST()函数和CONVERT()函数的效果一致,只是语法不同.前者更易使用,而后者的优势是格式化时间和数值.在以下这几种情况,二者一样: 1-1.SELECT CONVERT(de ...

  5. 使用register_shutdown_function触发写日志,使用fastcgi_finish_request提高响应速度

    公司内部的市场管理系统,一直是我一个人维护,最近老是有开发埋怨,内网的账号被人改了密码,账号被解绑了...哈的,错在这还不是一个完整的系统,既没有严格的权限也没有做操作日志呀... 权限现在是准备做在 ...

  6. Linux网络那点事

    跨平台系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#linux 之前的之前说过网络自连接的配置(CentOS服务器网络配置:http://ww ...

  7. android.util.Log常用方法

    android.util.Log常用的方法有以下5个: Log.v() Log.d() Log.i() Log.w() 以及 Log.e() .根据首字母分别对应VERBOSE,DEBUG,INFO, ...

  8. 容易忽略的z-index失效问题

    前些天写一个模仿虎牙网站幻灯片的插件,期间遇到我一直都没注意到的问题,就是z-idnex会失效的问题. 我是将幻灯片的左右按设置为float浮动的,然后在调试点击的时候发现无论怎么调高z-index都 ...

  9. “this kernel requires an x86-64 CPU, but only detects an i686 CPU, unable to boot” 问题解决

    1. 问题描述:  在Virtual Box上安装 Ubuntu 系统时出现错误(如题),VIrtual Box 上也没有64位操作系统的选项 2.原因分析: (1) 可能 BIOS 的 Virtua ...

  10. 美团点评DBProxy读写分离使用说明

    目的 因为业务架构上需要实现读写分离,刚好前段时间美团点评开源了在360Atlas基础上开发的读写分离中间件DBProxy,关于其介绍在官方文档已经有很详细的说明了,其特性主要有:读写分离.负载均衡. ...