Java8使用Stream将List转为Map的注意点

2022/3/30 9:19:44

本文主要是介绍Java8使用Stream将List转为Map的注意点,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 昨天QA同事给我提了一个Bug,后台配置的顺序跟浏览器展示页面的顺序不一致,感觉莫名其妙,于是进行debug追踪,模拟代码如下:

public class Example {


	private Long id;

	private String desc;


	public Long getId() {
		return id;
	}

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

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	@Override
	public String toString() {
		return "Example{" +
				"id=" + id +
				", desc='" + desc + '\'' +
				'}';
	}
}
public class Test {


	public static void main(String[] args) {

		List<Example> list = new ArrayList<>();

		for (long i = 1; i <=5; i++) {
			Example example = new Example();
			example.setId(new Random().nextLong());
			example.setDesc(String.valueOf(example.getId()));
			list.add(example);
		}

		list.forEach(System.out::println);


		System.out.println("====================");


		Map<Long, List<Example>> id2ExaMap = list.stream().collect(Collectors.groupingBy(Example::getId));

		id2ExaMap.forEach((id,example)->{
			System.out.println("id:" + id + " ,example" + example);
		});
	}
}

运行main方法后,控制台输出如下:
20211231153732

于是我的bug就诞生了。上网查了一下,解释如下:

image-20211231164204377

链接在这里

所以为了解决顺序问题,可以使用LinkedHashMap来进行接收。

public class Test {


	public static void main(String[] args) {
		List<Example> list = new ArrayList<>();

		for (long i = 1; i <=5; i++) {
			Example example = new Example();
			example.setId(new Random().nextLong());
			example.setDesc(String.valueOf(example.getId()));
			list.add(example);
		}

		list.forEach(System.out::println);


		System.out.println("====================");

		//这里使用LinkedHashMap来进行接收
		LinkedHashMap<Long, List<Example>> id2ExaMap = list.stream()
		.collect(Collectors
		.groupingBy(Example::getId, LinkedHashMap::new, Collectors.toList()));

		id2ExaMap.forEach((id,example)->{
			System.out.println("id:" + id + " ,example" + example);
		});
	}
}

运行main方法,控制台输出如下:

image-20211231172129326



这篇关于Java8使用Stream将List转为Map的注意点的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程