最近项目里streamAPI用的比较频繁,以前看过但是没怎么熟练使用,整理下常用的例子
User对象用来作为测试数据中的基础类

import java.io.Serializable;

public class User implements Serializable {

	private Long id;
	private String userName;
	private String userType;
	private String groupType;
	private String userCode;
	private String userTemp;

	public User(Long id, String userName, String userCode) {
		this.id = id;
		this.userName = userName;
		this.userCode = userCode;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	public String getGroupType() {
		return groupType;
	}

	public void setGroupType(String groupType) {
		this.groupType = groupType;
	}

	public String getUserCode() {
		return userCode;
	}

	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}

	public String getUserTemp() {
		return userTemp;
	}

	public void setUserTemp(String userTemp) {
		this.userTemp = userTemp;
	}
}

常用操作如下:


import java.util.*;
import java.util.stream.Collectors;

public class StreamApiDemo {

	private List<User> initData() {
		List<User> userList = new ArrayList<>();
		String stringUserNameFormat = "userName: %s";
		String userTypeFormat = "%s";
		String groupTypeFormat = "groupType: %s";
		String userCodeFormat = "userCode: %s";
		for (int i = 0; i < 10; i++) {
			User u = new User((long) i,
					String.format(stringUserNameFormat, String.valueOf(i)),
					String.format(userCodeFormat, String.valueOf(i)));
			u.setGroupType(String.format(groupTypeFormat, i / 2 == 0 ? "even" : "odd"));
			u.setUserType(String.format(userTypeFormat, i / 5 == 0 ? "0" : "1"));
			userList.add(u);
		}
		return userList;
	}

	public static void main(String... args) {
		StreamApiDemo streamApiDemo = new StreamApiDemo();
		List<User> userList = streamApiDemo.initData();
//		创建流
		streamApiDemo.createStream();
//		foreach
		streamApiDemo.forEachDemo();
//		Map操作
		streamApiDemo.mapDemo(userList);
//		filter操作
		streamApiDemo.filterDemo(userList);
//		limit操作
		streamApiDemo.limitDemo(userList);
//		sort操作
		streamApiDemo.sortDemo(userList);
//		collectors的toMap
		streamApiDemo.collectorsToMapDemo(userList);
//		collectors的groupingBy
		streamApiDemo.collectorsGroupByDemo(userList);
	}

	/**
	 * 根据对象的属性转换为map 如果key冲突根据k1值
	 * toMap参数:
	 * map中的key
	 * map中的value
	 * key冲突时返回的key
	 *
	 * @param list 测试集合
	 */
	private void collectorsToMapDemo(List<User> list) {
		Map<String, User> userTypeMap = list.stream().collect(Collectors.toMap(User::getUserCode, a -> a, (k1, k2) -> k1));
		for (String key : userTypeMap.keySet()) {
			System.out.println(userTypeMap.get(key).getUserName());
		}
	}

	/**
	 * 根据指定的属性给集合对象分组并返回map
	 *
	 * @param list 测试集合
	 */
	private void collectorsGroupByDemo(List<User> list) {
		Map<String, List<User>> userGroupMap = list.stream().collect(Collectors.groupingBy(User::getGroupType));
		for (String key : userGroupMap.keySet()) {
			List<User> userList = userGroupMap.get(key);
			userList.forEach(u -> System.out.println(u.getUserName()));
		}
	}

	/**
	 * 根据条件进行排序
	 * sorted的默认参数可以参考Comparator接口
	 * reverseOrder自然逆序
	 *
	 * @param list 测试集合
	 */
	private void sortDemo(List<User> list) {
		Random random = new Random(100);
		list.forEach(u -> u.setUserTemp(String.valueOf(random.nextInt())));
		List<User> userList = list.stream().sorted(Comparator.comparing(User::getUserTemp)).collect(Collectors.toList());
		userList.forEach(u -> System.out.println(u.getUserName()));
	}


	/**
	 * limit 方法用于获取指定数量的流
	 *
	 * @param list 测试集合
	 */
	private void limitDemo(List<User> list) {
		List<User> userList = list.stream().limit(5).collect(Collectors.toList());
		userList.forEach(u -> System.out.println(u.getUserName()));

		list.stream().limit(5).forEach(u -> System.out.println(u.getUserName()));
	}


	/**
	 * filter 方法用于通过设置的条件过滤出元素
	 * 获取userType为1的数据
	 * 获取userType为1的数量
	 *
	 * @param list 测试集合
	 */
	private void filterDemo(List<User> list) {
		List<User> userList = list.stream().filter(u -> u.getUserType().equals("1")).distinct().collect(Collectors.toList());
		userList.forEach(u -> System.out.println(u.getUserName()));
		Long userListNum = list.stream().filter(u -> u.getUserType().equals("1")).count();
		System.out.println(userListNum);

	}

	/**
	 * stream() − 为集合创建串行流。
	 * parallelStream() − 为集合创建并行流
	 * 使用filter过滤
	 */
	private void createStream() {
		List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
		List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
		filtered.forEach(System.out::println);
	}

	private void forEachDemo() {
		Random random = new Random();
		random.ints().limit(10).forEach(System.out::println);
	}

	/**
	 * map 方法用于映射每个元素到对应的结果
	 * 获取对象中属性并返回一个list
	 *
	 * @param list 测试集合
	 */
	private void mapDemo(List<User> list) {
		List<String> userNameList = list.stream().map(User::getUserName).distinct().collect(Collectors.toList());
		userNameList.forEach(System.out::println);
	}
}
posted on 2020-08-25 01:47  学业未成  阅读(358)  评论(0编辑  收藏  举报