代码之家  ›  专栏  ›  技术社区  ›  user3369592

使用Java 8将字符串转换为对象列表

  •  5
  • user3369592  · 技术社区  · 7 年前

    我有一根绳子

    "Red apple, blue banana, orange".
    

       Pattern pattern = Pattern.compile(", ");
       List<Fruit> f = pattern.splitAsStream(fruitString)
      .map(Fruit::valueOf)
      .collect(Collectors.toList());
    

    水果是枚举对象。基本上,如果我能够将字符串转换为某种格式,并且能够基于枚举名获得枚举对象。

    6 回复  |  直到 7 年前
        1
  •  3
  •   Sergey Kalinichenko    7 年前

    使用 map(...) 方法对原始对象执行转换 String . 而不是打电话 Fruit::valueOf 通过方法引用,在内部空间上拆分每个字符串 地图(…) ,并在正好得到两个部分时构造一个组合字符串:

    List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
    .map(s -> {
        String[] parts = s.split(" ");
        String tmp = parts.length == 2
        ? parts[0]+"_"+parts[1]
        : s;
        return Fruit.valueOf(tmp.toUpperCase());
    }).collect(Collectors.toList());
    

    Demo.

    如果需要对结果执行任何其他转换,可以在 return 陈述

        2
  •  2
  •   123-xyz    7 年前

    下面是另一个示例:

    f = pattern.splitAsStream(fruitString) 
            .map(s -> Arrays.stream(s.split(" ")).map(String::toUpperCase).collect(Collectors.joining("_"))) 
            .map(Fruit::valueOf).collect(Collectors.toList());
    

    或由 StreamEx :

    StreamEx.split(fruitString, ", ")
            .map(s -> StreamEx.split(s, " ").map(String::toUpperCase).joining("_"))
            .map(Fruit::valueOf).toList();
    
        3
  •  2
  •   Jigar Joshi    7 年前

    您的枚举

    static enum Fruit {
        RED_APPLE, BLUE_BANANA, ORANGE
    }
    

    主要代码:

    public static void main(String[] ar) throws Exception {
        Pattern pattern = Pattern.compile(", ");
        List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
                .map(YourClass::mapToFruit)
                .collect(Collectors.toList());
        System.out.println(f);
    }
    

    卸载脏映射部分的助手方法

    private static Fruit mapToFruit(String input) {
        String[] words = input.split("\\s");
        StringBuilder sb = new StringBuilder();
        if (words.length > 1) {
            for (int i = 0; i < words.length - 1; i++) {
                sb.append(words[i].toUpperCase());
                sb.append("_");
            }
            sb.append(words[words.length - 1].toUpperCase());
        } else {
            sb.append(words[0].toUpperCase());
        }
        return Fruit.valueOf(sb.toString());
    }
    
        4
  •  0
  •   Sean Powell    7 年前

    要拆分字符串,可以执行以下操作:

    string[] output = fruitString.split(",");
    

    然后,您必须逐字母遍历字符串以查找空格,并将其替换为字符串:`

    for(int i = 0; i < output.length; i++){
       for(int j = 0; j < output[i].length(); j++){
           char c = output[i].charAt(j);
           //check for space and replace with _
       }
    }
    

    然后使用。toUpperCase()将第一个字符转换为大写字母

    希望这对你有帮助。

        5
  •  0
  •   Karan    7 年前

    请查找以下代码,我已按照以下步骤操作:

    1) 首先将字符串拆分为。

    2) 再次将1)字符串的结果除以“”。

    演示: http://rextester.com/NNDF87070

    import java.util.*;
    import java.lang.*;
    
    class Rextester
    {  
           public static int WordCount(String s){
    
            int wordCount = 0;
    
            boolean word = false;
            int endOfLine = s.length() - 1;
    
            for (int i = 0; i < s.length(); i++) {
                // if the char is a letter, word = true.
                if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
                    word = true;
                    // if char isn't a letter and there have been letters before,
                    // counter goes up.
                } else if (!Character.isLetter(s.charAt(i)) && word) {
                    wordCount++;
                    word = false;
                    // last word of String; if it doesn't end with a non letter, it
                    // wouldn't count without this.
                } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
                    wordCount++;
                }
            }
            return wordCount;
        }
        public static void main(String args[])
        {
             String cord = "Red apple , blue banana, orange";
            String[] parts = cord.split(",");
            String[] result1 = new String[parts.length];
            for(int i=0; i<parts.length;i++) {
    
                String[] part2 = parts[i].split(" ");
    
                if(parts[i].length() > 1 && WordCount(parts[i]) > 1)
                {
                    String result = "_";
                    String uscore = "_";
                    for(int z =0; z < part2.length; z++)
                    {
                        if(part2.length > 1 ) {
                            if (z + 1 < part2.length) {
                                result = part2[z] + uscore + part2[z + 1];
                            }
                        }
                    }
    
                    result1[i] = result.toUpperCase();
                }
                else
                {
                    result1[i] = parts[i];
                }
    
            }
    
             for(int j =0 ; j <parts.length; j++)
            {
                System.out.println(result1[j]);
            }
    
        }
    }
    

    WordCount方法的参考: Count words in a string method?

        6
  •  0
  •   Jesse Fogel    7 年前
    String yourString = "Red apple, blue banana, orange";
    stringArray = yourString.split(", ");
    List<string> result;
    //stringArray will contain 3 strings
    //Red apple
    //blue banana
    //orange
    for(string s : stringArray) {
        //Replace all spaces with underscores
        result.add(s.replace(" ", "_").toUpperCase());
    }