ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java lambda表达式小技巧(一)分组groupingBy后保持排序不变

2020-12-23 11:59:49  阅读:815  来源: 互联网

标签:category index java groupingBy map put other 类别 lambda


问题

我的需求是查询出来一组数据后,按照其中的某个属性进行groupBy分组,分组后要保证顺序不变。
但是实际用groupBy进行分组后,返回的数据是杂乱无章的,没有按照原来list 的顺序返回。

排查

首先去api中查找问题原因,查看Javajava.util.streamCollectorsgroupingBy 方法实现,结果如下:

	//一个参数
	public static <T, K> Collector<T, ?, Map<K, List<T>>>
    groupingBy(Function<? super T, ? extends K> classifier) {
        return groupingBy(classifier, toList());
    }
	
	//实际调用方法
    public static <T, K, A, D>
    Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
                                          Collector<? super T, A, D> downstream) {
        return groupingBy(classifier, HashMap::new, downstream);
    }
	
	//两个参数
    public static <T, K, A, D>
    Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
                                          Collector<? super T, A, D> downstream) {
        return groupingBy(classifier, HashMap::new, downstream);
    }
    
	//三个参数
	public static <T, K, D, A, M extends Map<K, D>>
    Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,
                                  Supplier<M> mapFactory,
                                  Collector<? super T, A, D> downstream) {
        Supplier<A> downstreamSupplier = downstream.supplier();
        BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
        BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
            K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
            A container = m.computeIfAbsent(key, k -> downstreamSupplier.get());
            downstreamAccumulator.accept(container, t);
        };
        BinaryOperator<Map<K, A>> merger = Collectors.<K, A, Map<K, A>>mapMerger(downstream.combiner());
        @SuppressWarnings("unchecked")
        Supplier<Map<K, A>> mangledFactory = (Supplier<Map<K, A>>) mapFactory;

        if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
            return new CollectorImpl<>(mangledFactory, accumulator, merger, CH_ID);
        }
        else {
            @SuppressWarnings("unchecked")
            Function<A, A> downstreamFinisher = (Function<A, A>) downstream.finisher();
            Function<Map<K, A>, M> finisher = intermediate -> {
                intermediate.replaceAll((k, v) -> downstreamFinisher.apply(v));
                @SuppressWarnings("unchecked")
                M castResult = (M) intermediate;
                return castResult;
            };
            return new CollectorImpl<>(mangledFactory, accumulator, merger, finisher, CH_NOID);
        }
    }

可以发现 groupingBy调用是内部自己创建了一 HashMap(HashMap::new)。因为 HashMap,是无无序的,是根据keyhashcode进行hash,然后放入指定位置,所以按照一定顺序putHashMap时与遍历出HashMap的顺序不同。

因此我们直接调用三个参数的groupingBy方法mapFactory,传入有顺序的Map(LinkedHashMap) 就可以了。

示例

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {

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

		for (int i = 0; i < 3; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("index", 3);
			map.put("category", "类别3");
			map.put("other", i);
			list.add(map);
		}

		for (int i = 0; i < 3; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("index", 1);
			map.put("category", "类别1");
			map.put("other", i);
			list.add(map);
		}

		for (int i = 0; i < 3; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("index", 2);
			map.put("category", "类别2");
			map.put("other", i);
			list.add(map);
		}

		for (int i = 3; i < 6; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("index", 2);
			map.put("category", "类别1");
			map.put("other", i);
			list.add(map);
		}

		System.out.println(list);

		Map<String, List<Map<String, Object>>> step1 = list.stream().collect(Collectors.groupingBy(o -> {
			return o.get("category").toString();
		}));

		System.out.println(step1);

		// 手动控制排序方式
		Map<String, List<Map<String, Object>>> step2 = list.stream().sorted(Comparator.comparingInt(o -> {
			return -(int) o.get("index");
		})).collect(Collectors.groupingBy(o -> {
			return o.get("category").toString();
		}, LinkedHashMap::new, Collectors.toList()));

		System.out.println(step2);
	}

}

运行结果

[{other=0, index=3, category=类别3}, {other=1, index=3, category=类别3}, {other=2, index=3, category=类别3}, {other=0, index=1, category=类别1}, {other=1, index=1, category=类别1}, {other=2, index=1, category=类别1}, {other=0, index=2, category=类别2}, {other=1, index=2, category=类别2}, {other=2, index=2, category=类别2}, {other=3, index=2, category=类别1}, {other=4, index=2, category=类别1}, {other=5, index=2, category=类别1}]

{类别1=[{other=0, index=1, category=类别1}, {other=1, index=1, category=类别1}, {other=2, index=1, category=类别1}, {other=3, index=2, category=类别1}, {other=4, index=2, category=类别1}, {other=5, index=2, category=类别1}], 类别3=[{other=0, index=3, category=类别3}, {other=1, index=3, category=类别3}, {other=2, index=3, category=类别3}], 类别2=[{other=0, index=2, category=类别2}, {other=1, index=2, category=类别2}, {other=2, index=2, category=类别2}]}

{类别3=[{other=0, index=3, category=类别3}, {other=1, index=3, category=类别3}, {other=2, index=3, category=类别3}], 类别2=[{other=0, index=2, category=类别2}, {other=1, index=2, category=类别2}, {other=2, index=2, category=类别2}], 类别1=[{other=3, index=2, category=类别1}, {other=4, index=2, category=类别1}, {other=5, index=2, category=类别1}, {other=0, index=1, category=类别1}, {other=1, index=1, category=类别1}, {other=2, index=1, category=类别1}]}

标签:category,index,java,groupingBy,map,put,other,类别,lambda
来源: https://blog.csdn.net/ctwy291314/article/details/111581854

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有