首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以使用streams将字符串组合在一起并对有序Java列表中的组成员进行计数?

问是否可以使用streams将字符串组合在一起并对有序Java列表中的组成员进行计数?
EN

Stack Overflow用户
提问于 2017-09-01 18:50:14
回答 3查看 82关注 0票数 0

我有一个有序的字符串列表,假设是"aaa", "aaa", "aaa", "bbb", "bbb", "aaa"。我希望将相邻的相等字符串分组在一起,并对它们进行计数,因此操作的结果应该是如下所示的List:{"aaa":3}, {"bbb":2}, {"aaa", 1}。请注意,任务不是简单地按相同的值分组并对它们进行计数(否则我可以简单地使用带有counting的groupingBy ),而是只按具有相同值的相邻字符串进行分组,如果相同的字符串稍后出现在列表中,则应将其视为独立字符串。基本上,我需要这段代码在现有数据结构的基础上创建一个具有适当扩展的表头。

我想知道是否有一种合理的好方法来使用Java 8 streams来完成这项任务。我知道如何使用老式的循环,只是认为流可能提供了一种更好的方法。

EN

回答 3

Stack Overflow用户

发布于 2017-09-01 19:28:21

据我所知,您可以创建自定义收集器,但它与循环没有太大区别(将应用相同的逻辑)。还要注意,我使用SimpleEntry而不是Pair来保存列表中的每个元素。

代码语言:javascript
复制
private static Collector<String, ?, List<AbstractMap.SimpleEntry<String, Integer>>> adiacentCollector() {

    class Acc {

        private String previous;

        private List<AbstractMap.SimpleEntry<String, Integer>> result = new ArrayList<>();

        void accumulate(String elem) {
            if (previous == null) {
                previous = elem;
                result.add(new AbstractMap.SimpleEntry<String, Integer>(elem, 1));
                return;
            }

            if (previous.equals(elem)) {
                SimpleEntry<String, Integer> current = result.get(result.size() - 1);
                current.setValue(current.getValue() + 1);
                previous = elem;
            } else {
                SimpleEntry<String, Integer> oneMore = new SimpleEntry<String, Integer>(elem, 1);
                result.add(oneMore);
                previous = elem;
            }
        }

        Acc combine(Acc other) {

            SimpleEntry<String, Integer> lastEntry = result.get(result.size() - 1);
            SimpleEntry<String, Integer> firstEntry = other.result.get(0);

            if (lastEntry.getKey().equals(firstEntry.getKey())) {
                lastEntry.setValue(lastEntry.getValue() + firstEntry.getValue());
                other.result.remove(0);
            }

            result.addAll(other.result);

            return this;

        }

        List<AbstractMap.SimpleEntry<String, Integer>> finisher() {
            return result;
        }

    }
    return Collector.of(Acc::new, Acc::accumulate, Acc::combine, Acc::finisher);
}

并使用它:

代码语言:javascript
复制
 System.out.println(Stream.of("aaa", "aaa", "aaa", "bbb", "bbb", "aaa")
            .collect(adiacentCollector()));
票数 1
EN

Stack Overflow用户

发布于 2017-09-02 02:47:21

以下是由StreamEx提供的collapse API提供的解决方案

代码语言:javascript
复制
List<Map<String, Long>> res = StreamEx.of("aaa", "aaa", "aaa", "bbb", "bbb", "aaa")
        .collapse(Objects::equals, 
                  Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .toList();

System.out.println(res); // output: [{aaa=3}, {bbb=2}, {aaa=1}]

或者更简单的'runLength':

代码语言:javascript
复制
List<Map.Entry<String, Long>> res2 = StreamEx.of("aaa", "aaa", "aaa", "bbb", "bbb", "aaa")
                                             .runLengths().toList();

System.out.println(res2); // output: [{aaa=3}, {bbb=2}, {aaa=1}]
票数 1
EN

Stack Overflow用户

发布于 2017-09-02 03:35:05

StreamEx是最好的解决方案。但在这里,另一个使用闭包并减少流的方法:

闭包:

代码语言:javascript
复制
public class StatefulList {
    private List<Pair<String, Integer>> pairList;
    private int index = 0;

    public StatefulList() {
        this.pairList = new ArrayList<>();
    }

    public StatefulList add(String value) {
        if (pairList.size()==0) {
            pairList.add(new Pair<>(value, 1));
            return this;
        }
        Pair<String, Integer> last = pairList.get(index);
        if(last.getKey().equals(value)){
            pairList.set(index, new Pair<>(last.getKey(), last.getValue() + 1));
        } else {
            pairList.add(++index, new Pair<>(value, 1));
        }
        return this;
    }

    public String toString() {
        return pairList.toString();
    }
}

减少它:

代码语言:javascript
复制
Stream.of("aaa", "aaa", "aaa", "bbb", "bbb", "aaa")
      .reduce(new StatefulList(), StatefulList::add, (a,b) -> a);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45998611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档