java8 new features of functional programming paradigm

Given a string list of elements, as follows:

["1", "2", "bilibili", "of", "codesheep", "5", "at", "BILIBILI", "codesheep", "23", "CHEERS", "6"]

There are numeric strings, there are alphabetic string; string in uppercase, lowercase there; string length is long or short

Now write the code to complete a small feature :

I want to find all lengths> 5 = string, and ignoring case, deduplication string , then alphabetical order , and finally with "love ❤" into a string output!

First, I write a function, in the end determine the input string is alphabetic or numeric

public static Boolean isNum( String str ) {
	for( int i=0; i<str.length(); i++ ) {
		if(!Character.isDigit(str.charAt(i))) {
			return false;
		}
	}
	return true;
}

Then my meal SAO operations:

// 先定义一个具备按字母排序功能的Set容器,Set本身即可去重
Set<String> stringSet = newTreeSet<String>(new Comparator<String>() {
		@Override
		public int compare(String o1, String o2) {
			return o1.compareTo(o2);  // 按字母顺序排列
		}
	}
);

// 以下for循环完成元素去重、大小写转换、长度判断等操作
for( int i=0; i<list.size(); i++ ) {
	String s = list.get(i);
	if( !isNum(s) && s.length()>=5) {
		String sLower = s.toLowerCase(); 
		// 统一转小写
		stringSet.add( sLower );
	}
}

// 以下for循环完成连词成句
StringBuilder result = new StringBuilder();
for( String s : stringSet ) {
    result.append( s );
    result.append("❤"); // 用“爱心”连接符连接
}
String finalResult = result.substring(0,result.length()-1).toString();  // 去掉最后一个多余连接符
System.out.println( finalResult );

The final output is:

bilibili❤cheers❤codesheep

For the above operations, the operation flow a Java Stream 8, only one line of code can handle, for all loop Han ashes.

String result = list.stream()// 首先将列表转化为Stream流
.filter( i -> !isNum(i) )// 首先筛选出字母型字符串
.filter( i -> i.length() >= 5)// 其次筛选出长度>=5的字符串
.map( i -> i.toLowerCase() )// 字符串统一转小写
.distinct()                 // 去重操作来一下
.sorted( Comparator.naturalOrder() ) // 字符串排序来一下
.collect( Collectors.joining("❤") ); // 连词成句来一下,完美!

System.out.println(result);

In fact, it cited above have been set forth by way of a chestnut Java 8 functional programming paradigm: Stream flows elegant and powerful, especially when dealing with a collection of several in one step, Ga bang crisp.

Stream of course also just a Java 8 functional programming interface only, except Stream interfaces, there are other very powerful functional programming interfaces, such as:

  • Consumer Interface
  • Optional interfaces
  • Function Interface

A, Consumer Interface

As the name suggests, it is "the meaning of the consumer" and accept without argument the return value, give the most common chestnuts:

We usually print string, nature also accepts a parameter and print it out, we usually think about it, I would write:

System.out.println("hello world");     // 打印 hello world
System.out.println("hello codesheep"); // 打印 hello codesheep
System.out.println("bilibili cheers"); // 打印 bilibili cheers

Once you use the Consumer, always feel some of the more elegant

Consumer c = System.out::println;

c.accept("hello world");      // 打印 hello world
c.accept("hello codesheep");  // 打印 hello codesheep
c.accept("bilibili cheers");  // 打印 bilibili cheers

Consumer but it can also be used in combination with, to achieve the effect of multi-processing, such as:

c.andThen(c).andThen(c).accept("hello world");
// 会连续打印 3次:hello world

Of course, in this case just prints a string, is simple, if the business is more complex, Consumer reuse the convenience of not small.

Two, Function Interface

Meaning Function Interface stands for "function", in fact, a bit like the Consumer and above, but Function both input and output are also using more flexible, for example:

For example, I want a first integer multiplied by 2, and then calculates the square value

Function<Integer,Integer> f1 = i -> i+i;  // 乘以2功能
Function<Integer,Integer> f2 = i -> i*i;  // 平方功能
Consumer c = System.out::println;         // 打印功能

c.accept( f1.andThen(f2).apply(2) );      // 三种功能组合:打印结果 16

Among other things, this virtuoso operation or possible!

Three, Optional interfaces

Optional is essentially a container, you can put your variables referred to encapsulate it, so we do not explicitly on the original variables null value to detect and prevent the emergence of various null pointer exception. For example:

We want to write a program to obtain a student test scores as a function: getScore ()

public Integer getScore( Student student ) {
	if( student != null) {      // 第一层 null判空
		Subject subject = student.getSubject();
		if( subject != null) {  // 第二层 null判空
			return subject.score;
		}
	}
	return null;
}

Write down is not impossible, but we, as a "serious and conscientious" back-end engineers, so many nested if somewhat garish empty sentence!

To this end we must introduce Optional:

public Integer getScore( Student student ) {
	return Optional
	.ofNullable(student)
	.map( Student::getSubject )
	.map( Subject::getScore )
	.orElse(null);
}

Pretty! Nested if / else sentenced empty ashes!

Published 156 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_42590334/article/details/103957552