Collect HashSet / Java 8 / Regex Pattern / Stream API

后端 未结 6 768
日久生厌
日久生厌 2020-12-29 09:42

Recently I change version of the JDK 8 instead 7 of my project and now I overwrite some code snippets using new features that came with Java 8.

final Matcher         


        
6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 10:25

    Here is the implementation using Spliterator interface.

        // To get the required set
       Set result = (StreamSupport.stream(new MatcherGroupIterator(pattern,input ),false))
               .map( s -> s.toLowerCase() )
               .collect(Collectors.toSet());
        ...
        private static class MatcherGroupIterator implements Spliterator {
          private final Matcher matcher;
    
          public MatcherGroupIterator(Pattern p, String s) {
            matcher = p.matcher(s);
          }
    
          @Override
          public boolean tryAdvance(Consumer action) {
            if (!matcher.find()){
                return false;
            }
            action.accept(matcher.group());
            return true;
          }
    
          @Override
          public Spliterator trySplit() {
            return null;
          }
    
          @Override
          public long estimateSize() {
            return Long.MAX_VALUE;
          }
    
          @Override
          public int characteristics() {
            return Spliterator.NONNULL;
          }
      }
    

提交回复
热议问题