Java - 由Regex过滤列表条目

时间:2014-07-17 07:55:01

标签: java regex collections

我的代码如下所示:

List<String> filterList(List<String> list, String regex) {
  List<String> result = new ArrayList<String>();
  for (String entry : list) {
    if (entry.matches(regex)) {
      result.add(entry);
    }
  }
  return result;
}

它返回一个列表,其中只包含与regex匹配的条目。 我想知道是否有这样的内置功能:

List<String> filterList(List<String> list, String regex) {
  List<String> result = new ArrayList<String>();
  result.addAll(list, regex);
  return result;
}

3 个答案:

答案 0 :(得分:51)

除了Konstantin的回答:Java 8通过PatternasPredicate课程中添加Matcher.find()支持,Pattern pattern = Pattern.compile("..."); List<String> matching = list.stream() .filter(pattern.asPredicate()) .collect(Collectors.toList()); 内部调用local playerInfo = {} if player then local newPlayer = {NAME = name, HP = 10, DMG = 4} table.insert(playerInfo, newPlayer) end for k, v in pairs(playerInfo) do print(v.NAME) end

public static String buildPostParameters(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (hashMap != null) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
        URL url = new URL(apiAddress);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals("GET"));
        urlConnection.setRequestMethod(method);

        urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);        

        urlConnection.setRequestProperty("Content-Type", mimeType);
        OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(requestBody);
        writer.flush();
        writer.close();
        outputStream.close();            

        urlConnection.connect();

        return urlConnection;
    }

太棒了!

答案 1 :(得分:18)

在java 8中,您可以使用新的stream API

执行此类操作
List<String> filterList(List<String> list, String regex) {
    return list.stream().filter(s -> s.matches(regex)).collect(Collectors.toList());
}

答案 2 :(得分:3)

Google的Java库(Guava)有一个界面Predicate<T>,可能对你的情况非常有用。

static String regex = "yourRegex";

Predicate<String> matchesWithRegex = new Predicate<String>() {
        @Override 
        public boolean apply(String str) {
            return str.matches(regex);
        }               
};

您可以定义类似上面的谓词,然后使用单行代码根据此谓词过滤列表:

Iterable<String> iterable = Iterables.filter(originalList, matchesWithRegex);

要将iterable转换为列表,您可以再次使用Guava:

ArrayList<String> resultList = Lists.newArrayList(iterable);