【问题标题】:convert a string to a list of object using Java 8使用 Java 8 将字符串转换为对象列表
【发布时间】:2018-04-27 21:01:55
【问题描述】:

我有一个字符串

"Red apple, blue banana, orange".

我怎么能先用“,”分割它,然后在两个单词之间添加“_”(例如 Red_apple 但不是橙色)并将所有字母大写。我阅读了一些帖子并找到了解决方案,但它只有拆分部分,我怎么能添加“_”并将所有字母大写? :

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

Fruit 是一个枚举对象。因此,基本上,如果我能够将字符串转换为某种格式,并且能够根据 Enum 名称获取 Enum 对象。

【问题讨论】:

  • 另一种解决方案Arrays.asList(str.split(",")).stream() .map(s-&gt;s.replace(' ', '_')).map(String::toUpperCase) .collect(Collectors.toList());

标签: java regex string java-8 java-stream


【解决方案1】:

使用map(...) 方法对原始String 执行转换。与其通过方法引用调用Fruit::valueOf,不如在map(...) 内的空间上拆分每个字符串,并在得到正好两部分时构造一个组合字符串:

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 语句之前的同一 lambda 代码块中进行。

【讨论】:

  • 感谢您的回复。我实际上需要输出是一个 Fruit 列表并将包括橙色在内的所有字母大写。
  • 为什么不用简单的String tmp = s.replace(' ', '_'); 而不是这个巴洛克式的String[] parts = s.split(" "); String tmp = parts.length == 2? parts[0]+"_"+parts[1]: s;?
【解决方案2】:

这是另一个示例:

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】:

    你的枚举

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

    【讨论】:

    • 令人惊讶的是,有多少用户忘记了,如何进行简单的“将一个字符替换为另一个”操作......如果replace(' ', '_')太简单了(OP没有说明处理任意空格是必要的),你可以使用replaceAll("\\s", "_")...
    【解决方案4】:

    要拆分字符串,您可以这样做:

    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】:

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

      1) 首先用 , 分割字符串。

      2) 再次将 1) 字符串的结果用 " " 分割。

      3) 然后如果字数大于 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】:
        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());
        }
        

        【讨论】:

        • 我很高兴至少有一位用户记得.replace(" ", "_")。但是,您的代码完全没有抓住重点,因为将数组重新组装为单个字符串并不是 OP 想要的。此外,for(string s in stringArray) 不是有效的 Java 代码……
        猜你喜欢
        • 2016-08-01
        • 2019-01-17
        • 1970-01-01
        • 2018-03-26
        • 2015-02-25
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        相关资源
        最近更新 更多