2016-05-24 4 views
2

ですべての文字列のリストを収集:Stream<String>考える私は現在、次のエクササイズで苦労していた最大の長さ

は(Collectorを使用して)最大な長さを持つすべてのStringの のコレクションを収集します。ここで

私が試したものです:

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を作成し、それをtravesrseしてSetを作成し、それをトラバースして最大-を取得します。

+3

私はこれがあなたの質問に答えると信じhttp://stackoverflow.com/questions/29334404/how-to- force-max-to-return-all-java-stream-in-a-java-stream Stringの長さを比較するコンパレータで、そこの答えを使用することができます。しかし、はい、それをワンパスしたい場合は、カスタムコレクタを用意する必要があります。 – Tunaki

答えて

4

私はこのようにそれを行うだろう:

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 
関連する問題