【问题标题】:Collecting a List of all strings with maximum length [duplicate]收集具有最大长度的所有字符串的列表 [重复]
【发布时间】:2016-05-24 15:04:35
【问题描述】:

我目前正在努力进行以下练习:

给定一个Stream<String> 收集(使用Collector)所有Strings 的集合 最大长度。

这是我尝试过的:

private static class MaxStringLenghtCollector 
                    implements Collector<String, List<String>, List<String>> {

    @Override
    public Supplier<List<String>> supplier() {
        return LinkedList::new;
    }
    @Override
    public BiConsumer<List<String>, String> accumulator() {
        return (lst, str) -> {
            if(lst.isEmpty() || lst.get(0).length() == str.length())
                lst.add(str);
            else if(lst.get(0).length() < str.length()){
                lst.clear();
                lst.add(str);
            }                   
        };
    }

    @Override
    public BinaryOperator<List<String>> combiner() {
        return (lst1, lst2) -> {
            lst1.addAll(lst2);
            return lst1;
        };
    }

    @Override
    public Function<List<String>, List<String>> finisher() {
        return Function.identity();
    }

    @Override
    public Set<java.util.stream.Collector.Characteristics> characteristics() {
        return EnumSet.of(Characteristics.IDENTITY_FINISH);
    }
}

所以我写了我的自定义收集器来完成这项工作,但是......它看起来确实很丑。也许有一些标准的方法可以做到这一点。例如,我会尝试分组收集器:

public static Collection<String> allLongest(Stream<String> str){
    Map<Integer, List<String>> groups = str.collect(Collectors.groupingBy(String::length));
    return groups.get(groups.keySet()
                    .stream()
                    .mapToInt(x -> x.intValue())
                    .max()
                    .getAsInt());
}

但这既丑陋又低效。首先,我们构建一个Map,然后遍历它构建一个Set,然后遍历它得到max-List

【问题讨论】:

  • 我相信这回答了您的问题stackoverflow.com/questions/29334404/… 您可以将答案与比较字符串长度的比较器一起使用。但是,是的,如果你想一次性完成,你需要有一个自定义收集器。

标签: java java-8


【解决方案1】:

我会这样做:

List<String> values = Arrays.asList("abc", "ab", "bc", "bcd", "a");
// I group by length and put it into a TreeMap then get the max value
values.stream().collect(groupingBy(String::length, TreeMap::new, toList()))
    .lastEntry()
    .getValue()
    .forEach(System.out::println);

输出:

abc
bcd

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 2018-10-20
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多