[英]Converting String from arraylist to another String
Say I have the following Arraylist:假设我有以下 Arraylist:
1. [123] [456] [789]
2. [134] [105] [455]
And have to follow the rules:并且必须遵守规则:
[123] [456] = cat
[789] = dog
[134] = mouse
[105] [455] = snake
And from Arraylist 1, I want to form the new following Array list:从 Arraylist 1 开始,我想形成以下新的 Array 列表:
Is there anyway to do that.有没有办法做到这一点。 I currently haven't found anything for String to String conversion.
我目前还没有找到任何字符串到字符串转换的内容。
Here is a way to do this.这里有一种方法可以做到这一点。 This is only one of many possible ways;
这只是众多可能方式中的一种; there maybe even better ways than this.
也许还有比这更好的方法。 You may consider this just an indicator of how to do this.
您可能认为这只是如何执行此操作的一个指标。 The interesting class is the
Rules
class.有趣的类是
Rules
类。 This has the conversion rules implemented as java.util.Pattern
instances and the apply()
method in it does the conversion.这将转换规则实现为
java.util.Pattern
实例,其中的apply()
方法进行转换。
If you have input array of some other type than String
, you may follow the general idea but a Pattern
based implementation may not always work.如果您有其他类型的输入数组而不是
String
,您可以遵循一般思想,但基于Pattern
的实现可能并不总是有效。
public class ListOfStringsToAnother{
public static void main( String[] args ){
List<String> inputStrings = getInputArray();
List<String> output = new ArrayList<>();
for( String input : inputStrings ) {
output.add( Rules.INSTANCE.apply( input ) );
}
output.forEach( System.out::println );
}
private static List<String> getInputArray(){
List<String> list = Arrays.asList( "[123] [456] [789]", "[134] [105] [455]" );
return list;
}
private static final class Rules{
static Map<String, Pattern> patterns = new HashMap<>();
static Rules INSTANCE = new Rules();
private Rules() {
patterns.put( "cat", Pattern.compile( "\\[123\\] \\[456\\]", Pattern.CASE_INSENSITIVE ) );
patterns.put( "dog", Pattern.compile( "\\[789\\]", Pattern.CASE_INSENSITIVE ) );
patterns.put( "mouse", Pattern.compile( "\\[134\\]", Pattern.CASE_INSENSITIVE ) );
patterns.put( "snake", Pattern.compile( "\\[105\\] \\[455\\]", Pattern.CASE_INSENSITIVE ) );
}
String apply( String input ) {
/* Apply your rules here. Change this logic based on the outcome you need. */
for( Entry<String, Pattern> e : patterns.entrySet() ) {
Pattern p = e.getValue();
input = p.matcher( input ).replaceAll( e.getKey() ); //This replaces the original strings in the input
}
return input;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.