Java Stream维护Collectors.groupingBy()生成的Map顺序

时间:2017-09-15 17:55:05

标签: java-8 stream java-stream

我有一个String类型的数据列表,试图将每个字符串的计数设为Map<String, Long>

List<String> dataList = new ArrayList();
dataList.addAll(Arrays.asList(new String[] {"a", "z", "c", "b", "a"}));
System.out.println(dataList.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting())));

输出为{a=2, b=2, c=1, z=1}。我希望输出保持列表中提供的顺序。比如,{a=2, z=1, c=1, b=2}

LinkedHashMap会维护订单,但不确定如何使用Collectors.groupingBy()将输出转换为LinkedHashMap

尝试使用Java8-stream

解决问题

3 个答案:

答案 0 :(得分:2)

Per JB Nizet dataList.stream().collect(Collectors.groupingBy(w -> w, LinkedHashMap::new, Collectors.counting()))

答案 1 :(得分:2)

对于这种情况,您应该使用Set Cookie功能:

代码示例:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        <!--
            function WriteCookie()
            {
                if( document.myform.customer.value == ""){ 
                    alert("Enter a name");
                    return;
                }
                cookievalue = escape(document.myform.customer.value) + ";";
                document.cookie="name=" + cookievalue;
                document.write("Setting Cookies : " + document.cookie);
            }
        //-->
    </script>
</head>
<body>
    <form name="myform" action ="">
        Enter name: <input type="text" name="customer"/>
        <input type="button" value="Set Cookie" onlick="WriteCookie();"/>
    </form>
</body>
</html>

输出:

groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory,Collector<? super T,A,D> downstream)

参考文献:Oracle Documentation

答案 2 :(得分:0)

不像给定的解决方案那么简单,只是为了说明:您也可以使用TreeMap,使用合适的Comparator,例如:

List<Character> list = Arrays.asList('q', 'a', 'z', 'c', 'b', 'z', 'a');
Comparator<Character> comp = Comparator.comparing(list::indexOf);
Map<Character, Long> map = list.stream()
    .collect(groupingBy(c -> c, () -> new TreeMap<>(comp), counting()))
;
System.out.println(map);