简体   繁体   中英

Converting String from arraylist to another String

Say I have the following 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:

  1. cat dog
  2. mouse snake

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. This has the conversion rules implemented as java.util.Pattern instances and the apply() method in it does the conversion.

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.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM