簡體   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