Java8排序stream.sorted()

在这个页面上我们将提供java 8 Stream sorted()示例。我们可以按照自然排序以及Comparator提供的排序对流进行排序。在java 8中Comparator可以使用lambda表达式进行实例化。我们还可以反转自然排序以及提供的排序Comparator。自然排序使用提供的顺序Comparable,必须由其实例是流元素的类实现。在这个页面上我们将排序List,Map并Set使用java 8流sorted()方法。
1.sorted()方法的语法示例。

1.1sorted():它使用自然顺序对流的元素进行排序。元素类必须实现Comparable接口。

按自然升序对集合进行排序

list.stream().sorted() .stream().sorted();

自然序降序使用Comparator提供reverseOrder()方法

list.stream().sorted(Comparator.reverseOrder()) .stream().sorted(Comparator.reverseOrder());

1.2 sorted(Comparator<? super T> comparator):这里我们创建一个Comparator使用lambda表达式的实例。我们可以按升序和降序对流元素进行排序。

使用Comparator来对列表进行自定义升序。

list.stream().sorted(Comparator.comparing(Student::getAge)) .stream().sorted(Comparator.comparing(Student::getAge));

使用Comparator提供reversed()方法来对列表进行自定义降序。 。

list.stream().sorted(Comparator.comparing(Student::getAge).reversed()) .stream().sorted(Comparator.comparing(Student::getAge).reversed());

2.使用List流排序()

package com.stream.demo;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
 
public class StreamListDemo {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<>();
		list.add(new Student(1, "Mahesh", 12));
		list.add(new Student(2, "Suresh", 15));
		list.add(new Student(3, "Nilesh", 10));
 
		System.out.println("---Natural Sorting by Name---");
		List<Student> slist = list.stream().sorted().collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Natural Sorting by Name in reverse order---");
		slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age---");
		slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age with reverse order---");
		slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
	}
}
 
package com.stream.demo;

public class Student implements Comparable<Student> {
   private int id;
   private String name;
   private int age;

   public Student(int id, String name, int age) {
   	this.id = id;
   	this.name = name;
   	this.age = age;
   }

   public int getId() {
   	return id;
   }

   public String getName() {
   	return name;
   }

   public int getAge() {
   	return age;
   }

   @Override
   public int compareTo(Student ob) {
   	return name.compareTo(ob.getName());
   }

   @Override
   public boolean equals(final Object obj) {
   	if (obj == null) {
   		return false;
   	}
   	final Student std = (Student) obj;
   	if (this == std) {
   		return true;
   	} else {
   		return (this.name.equals(std.name) && (this.age == std.age));
   	}
   }

   @Override
   public int hashCode() {
   	int hashno = 7;
   	hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
   	return hashno;
   }
}

执行结果

---Natural Sorting by Name---
Id:1, Name: Mahesh, Age:12
Id:3, Name: Nilesh, Age:10
Id:2, Name: Suresh, Age:15
---Natural Sorting by Name in reverse order---
Id:2, Name: Suresh, Age:15
Id:3, Name: Nilesh, Age:10
Id:1, Name: Mahesh, Age:12
---Sorting using Comparator by Age---
Id:3, Name: Nilesh, Age:10
Id:1, Name: Mahesh, Age:12
Id:2, Name: Suresh, Age:15
---Sorting using Comparator by Age with reverse order---
Id:2, Name: Suresh, Age:15
Id:1, Name: Mahesh, Age:12
Id:3, Name: Nilesh, Age:10

3.使用set流排序

package com.stream.demo;
 
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
 
public class StreamSetDemo {
	public static void main(String[] args) {
		Set<Student> set = new HashSet<>();
		set.add(new Student(1, "Mahesh", 12));
		set.add(new Student(2, "Suresh", 15));
		set.add(new Student(3, "Nilesh", 10));
 
		System.out.println("---Natural Sorting by Name---");
		System.out.println("---Natural Sorting by Name---");
		set.stream().sorted().forEach(e -> System.out.println("Id:"
						+ e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Natural Sorting by Name in reverse order---");
		set.stream().sorted(Comparator.reverseOrder()).forEach(e -> System.out.println("Id:"
						+ e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age---");
		set.stream().sorted(Comparator.comparing(Student::getAge))
						.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age in reverse order---");
		set.stream().sorted(Comparator.comparing(Student::getAge).reversed())
						.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
	}
}

4.使用Map流排序

package com.stream.demo;
 
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
 
public class StreamMapDemo {
	public static void main(String[] args) {
		Map<Integer, String> map = new HashMap<>();
		map.put(15, "Mahesh");
		map.put(10, "Suresh");
		map.put(30, "Nilesh");
 
		System.out.println("---Sort by Map Value---");
		map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
						.forEach(e -> System.out.println("Key: "+ e.getKey() +", Value: "+ e.getValue()));
 
		System.out.println("---Sort by Map Key---");System.out.println("---Sort by Map Key---");
		map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
						.forEach(e -> System.out.println("Key: "+ e.getKey() +", Value: "+ e.getValue()));
	}
}

————————————————
原文链接:https://blog.csdn.net/qq_34996727/article/details/94472999

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
优化这段代码:List<CompletableFuture<CallIntersectionVo>> futureList = Lists.newArrayList(); for (Map.Entry<String, List<String>> entry : intersectionResult.entrySet()) { CompletableFuture<CallIntersectionVo> future = CompletableFuture.supplyAsync(() -> { String account = entry.getKey(); List<String> personNoList = entry.getValue().stream().distinct().collect(Collectors.toList()); CallIntersectionVo vo = new CallIntersectionVo(); if (personNoList.size() >= 2) { List<PersonBasicVo> personVoList = Lists.newArrayList(); int count = 0; for (String personNo : personNoList) { Map<String, Object> callMap = callMapList.stream().filter(map -> personNo.equals(map.get("personNo"))).findAny().get(); List<CallRecord> callList = (List<CallRecord>) callMap.get("callList"); // 统计通话频率 count += callList.stream().filter(x -> account.equals(x.getRelationshipAccount())).count(); // 获取涉案人 personVoList.add(personList.stream().filter(person -> personNo.equals(person.getPersonNo())).findAny().get()); } // 共同号码是否属于涉案人 String commonPersonName = getCommonPersonName(personList, account); if (frequency != null && frequency > 0) { if (count >= frequency) { vo.setPersons(personVoList); vo.setCommonAccount(account); vo.setFrequency(count); vo.setCommonPersonName(commonPersonName); } return vo; } else { vo.setPersons(personVoList); vo.setCommonAccount(account); vo.setFrequency(count); vo.setCommonPersonName(commonPersonName); return vo; } } else { return vo; } }, executor); futureList.add(future); } voList.addAll(futureList.stream().map(CompletableFuture::join) .distinct().sorted(Comparator.comparing(vo -> vo.getPersons().size())) .collect(Collectors.toList()));
07-13
优化后的代码如下: ```java List<CompletableFuture<CallIntersectionVo>> futureList = intersectionResult.entrySet().stream() .map(entry -> CompletableFuture.supplyAsync(() -> { String account = entry.getKey(); List<String> personNoList = entry.getValue().stream().distinct().collect(Collectors.toList()); CallIntersectionVo vo = new CallIntersectionVo(); if (personNoList.size() >= 2) { List<PersonBasicVo> personVoList = personNoList.stream() .map(personNo -> { Map<String, Object> callMap = callMapList.stream() .filter(map -> personNo.equals(map.get("personNo"))) .findAny() .orElseThrow(() -> new NoSuchElementException("Person not found")); List<CallRecord> callList = (List<CallRecord>) callMap.get("callList"); int count = (int) callList.stream().filter(x -> account.equals(x.getRelationshipAccount())).count(); return personList.stream() .filter(person -> personNo.equals(person.getPersonNo())) .findAny() .orElseThrow(() -> new NoSuchElementException("Person not found")); }) .collect(Collectors.toList()); String commonPersonName = getCommonPersonName(personList, account); vo.setPersons(personVoList); vo.setCommonAccount(account); vo.setFrequency(personVoList.size()); vo.setCommonPersonName(commonPersonName); return vo; } else { return vo; } }, executor)) .collect(Collectors.toList()); List<CallIntersectionVo> voList = futureList.stream() .map(CompletableFuture::join) .distinct() .sorted(Comparator.comparingInt(vo -> vo.getPersons().size())) .collect(Collectors.toList()); ``` 主要优化: 1. 使用流式编程,替换原来的for循环和entrySet遍历。 2. 使用`stream()`和`collect(Collectors.toList())`方法来收集结果,代替手动添加到列表中。 3. 使用`orElseThrow`方法来处理可能找不到元素的情况,避免空指针异常。 4. 将lambda表达式内联,使代码更简洁。 5. 使用`Comparator.comparingInt`方法来指定排序规则,避免编译器警告。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值