繁体   English   中英

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

[英]convert a string to a list of object using Java 8

我有一个字符串

"Red apple, blue banana, orange".

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

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

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

使用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());

演示。

如果需要对结果执行任何其他转换,可以在return语句之前的相同lambda代码块中执行它们。

你的枚举

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

Helper方法卸载脏映射部分

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

这是另一个例子:

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

要分割字符串,您可以:

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()将第一个char转换为大写字母

希望这对你有所帮助。

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

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方法的参考: 计算字符串方法中的单词?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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