This is my code
List ints = Stream.of(1,2,4,3,5).collect(Collectors.toList());
Integer maxInt = ints.stream()
.max(Comparator.comparing(i -> i))
.get();
System.out.println("Maximum number in the set is " + maxInt);
output:
Maximum number in the set is 5
I cannot make distingues between two i in below section of my code
Comparator.comparing(i -> i)
can anyone be kind and explain the difference between two i?
解决方案
The method Comparator.comparing(…) is intended to create a Comparator which uses an order based on a property of the objects to compare. When using the lambda expression i -> i, which is a short writing for (int i) -> { return i; } here, as a property provider function, the resulting Comparator will compare the values itself. This works when the objects to compare have a natural order as Integer has.
So
Stream.of(1,2,4,3,5).max(Comparator.comparing(i -> i))
.ifPresent(maxInt->System.out.println("Maximum number in the set is " + maxInt));
does the same as
Stream.of(1,2,4,3,5).max(Comparator.naturalOrder())
.ifPresent(maxInt->System.out.println("Maximum number in the set is " + maxInt));
though the latter is more efficient as it is implemented as singleton for all types which have a natural order (and implement Comparable).
The reason why max requires a Comparator at all, is because you are using the generic class Stream which might contain arbitrary objects.
This allows, e.g. to use it like streamOfPoints.max(Comparator.comparing(p->p.x)) to find the point with the largest x value while Point itself does not have a natural order. Or do something like streamOfPersons.sorted(Comparator.comparing(Person::getAge)).
When using the specialized IntStream you can use the natural order directly which is likely to be more efficient:
IntStream.of(1,2,4,3,5).max()
.ifPresent(maxInt->System.out.println("Maximum number in the set is " + maxInt));
To illustrate the difference between “natural order” and a property based order:
Stream.of("a","bb","aaa","z","b").max(Comparator.naturalOrder())
.ifPresent(max->System.out.println("Maximum string in the set is " + max));
this will print
Maximum string in the set is z
as the natural order of Strings is the lexicographical order where z is greater than b which is greater than a
On the other hand
Stream.of("a","bb","aaa","z","b").max(Comparator.comparing(s->s.length()))
.ifPresent(max->System.out.println("Maximum string in the set is " + max));
will print
Maximum string in the set is aaa
as aaa has the maximum length of all Strings in the stream. This is the intended use case for Comparator.comparing which can be made even more readable when using method references, i.e. Comparator.comparing(String::length) which almost speaks for itself…
______________________________________________________________________________________________________________________________________________________________
jdk8 Lambda表达式 集合过滤,排序,最大值,最小值,平均值等操作
packagecn.sh.ideal.jdk8;importcn.sh.ideal.bean.UserBean;import java.util.*;importjava.util.function.Function;importjava.util.stream.Collectors;importjava.util.stream.Stream;/*** Lambda表达式写法
*
*@authorgilbert*/
public classLambdaDemo {/*** 功能描述 无参无返回值
*
*@paramlist
*@returnvoid
*@authorgilbert
* @date 2019/6/12*/
public static void lambdaWithParamAndNoReturn(Listlist) {
list.forEach(userBean-> System.out.println("hello," +userBean.getUsername()));
}/***功能描述 重新封装集合数据
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void initList(Listlist){
List userList = list.stream().map(userBean -> newUserBean(userBean.getUserid(), userBean.getWorkid(), userBean.getUsername())).collect(Collectors.toList());
userList.forEach(userBean-> System.out.println("new list:" +userBean.getUsername()));
}/***功能描述 集合过滤
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void filterList(Listlist){//List filterList = list.stream().filter(userBean -> userBean.getUsername().contains("g")).collect(Collectors.toList());
List filterList = list.stream().filter(userBean -> Integer.valueOf(userBean.getUserid()) > 6).collect(Collectors.toList());
filterList.forEach(userBean-> System.out.println("filter list:" +userBean.getUsername()));
}/***功能描述 排序
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void sortList(Listlist){//按userid排序
List sortList = list.stream().sorted((userBean1,userBean2) ->userBean1.getUsername().compareTo(userBean2.getUsername())).collect(Collectors.toList());
sortList.forEach(userBean-> System.out.println("sortList:" + userBean.getUserid() + "," +userBean.getUsername()));
}/***功能描述 多条件排序
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void multiSortList(Listlist){
list.sort(Comparator.comparing(UserBean::getUserid).thenComparing(UserBean::getUsername));
list.forEach(userBean-> System.out.println("multiSortList:" + userBean.getUserid() + "," +userBean.getUsername()));
}/***功能描述 倒序
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void reversedSortList(Listlist){//第一种写法
Comparator comparator = (userBean1,userBean2) ->userBean1.getUsername().compareTo(userBean2.getUsername());
list.sort(comparator.reversed());//第二种写法//list.sort(Comparator.comparing(UserBean::getUserid).reversed());
list.forEach(userBean-> System.out.println("reverseSortList:" + userBean.getUserid() + "," +userBean.getUsername()));
}/***功能描述 多条件倒序
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void multiReversedSortList(Listlist){
list.sort(Comparator.comparing(UserBean::getUserid).thenComparing(UserBean::getUsername).reversed());
list.forEach(userBean-> System.out.println("multiReversedSortList:" + userBean.getUserid() + "," +userBean.getUsername()));
}/***功能描述 集合分组
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void groupByList(Listlist){
Map> groupByMap =list.stream().collect(Collectors.groupingBy(UserBean::getWorkid));
groupByMap.forEach((k,v)-> System.out.println(k+"," +v));
}/***功能描述 求和
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void sumByList(Listlist){
System.out.println("sum="+list.stream().mapToInt(UserBean::getUserid).sum());
}/***功能描述 最大值
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void maxByList(Listlist){
OptionalInt optional=list.stream().mapToInt(UserBean::getUserid).max();
System.out.println("max=" +optional.getAsInt());
}/***功能描述 最小值
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void minByList(Listlist){
OptionalInt optional=list.stream().mapToInt(UserBean::getUserid).min();
System.out.println("min=" +optional.getAsInt());
}/***功能描述 平均值
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void averageByList(Listlist){
OptionalDouble optionalDouble=list.stream().mapToInt(UserBean::getUserid).average();
System.out.println("average=" +optionalDouble.getAsDouble());
}/***功能描述 List转map
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void listToMap(Listlist){//用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
Map map = list.stream().collect(Collectors.toMap(UserBean::getUserid,userBean -> userBean, (k1, k2) ->k1));
map.forEach((k,v)-> System.out.println("k=" + k + ",v=" +v));
}/***功能描述 map转list
*@authorgilbert
* @date 2019/6/12
*@param[map]
*@returnvoid*/
public static void mapToList(Mapmap){
List list = map.entrySet().stream().sorted(Comparator.comparing(key -> key.getKey())).map(key -> newUserBean(Integer.valueOf(key.getKey()),key.getValue(),key.getValue())).collect(Collectors.toList());
list.forEach(userBean-> System.out.println(userBean.getUserid() + "," +userBean.getUsername()));
}/***功能描述 字符串转list
*@authorgilbert
* @date 2019/6/12
*@param[str]
*@returnvoid*/
public static voidstringToList(String str){//不需要处理// list = Arrays.asList(str.split(","));//需要处理
List list = Arrays.asList(str.split(",")).stream().map(string ->String.valueOf(string)).collect(Collectors.toList());
list.forEach(string->System.out.println(string));
}/***功能描述 姓名以逗号拼接
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void joinStringValueByList(Listlist){
System.out.println(list.stream().map(UserBean::getUsername).collect(Collectors.joining(",")));
}/***功能描述 分组统计
*@authorgilbert
* @date 2019/6/12
*@param[list]
*@returnvoid*/
public static void countByList(Listlist){
Map map =list.stream().collect(Collectors.groupingBy(UserBean::getWorkid,Collectors.counting()));
map.forEach((k,v)-> System.out.println("key=" + k + ",value=" +v));
}public static voidmain(String[] args) {//List list = Arrays.asList(new UserBean(1, "AKB001", "gilbert"), new UserBean("2", "AKB002", "apple"), new UserBean("3", "AKB003", "cat"));
List list = Stream.of(new UserBean(1, "AKB001", "gilbert"),new UserBean(2, "AKB002", "apple"),new UserBean(4, "AKB004", "dog"),new UserBean(5, "AKB005", "egg"),new UserBean(6, "AKB006", "frog"),new UserBean(6, "AKB006", "banana"),new UserBean(7, "AKB007", "google"),new UserBean(3, "AKB003", "cat"))
.collect(Collectors.toList());
lambdaWithParamAndNoReturn(list);
initList(list);
filterList(list);
sortList(list);
reversedSortList(list);
multiSortList(list);
multiReversedSortList(list);
groupByList(list);
sumByList(list);
maxByList(list);
minByList(list);
averageByList(list);
listToMap(list);
String str= "apple,banana,cat,dog";
stringToList(str);
Map map =new HashMap() {
{
put(1, "apple");
put(2, "banana");
put(3, "cat");
put(4, "dog");
put(5, "frog");
}
};
mapToList(map);
joinStringValueByList(list);
countByList(list);
}
}