Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a string to a list of object using Java 8

I have a string

"Red apple, blue banana, orange".

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

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

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

like image 626
user3369592 Avatar asked Nov 14 '17 19:11

user3369592


3 Answers

Use map(...) method to perform transformations on the original String. Instead of calling Fruit::valueOf through a method reference, split each string on space inside map(...), and construct a combined string when you get exactly two parts:

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.

If you need to perform any additional transformations of the result, you can do them in the same lambda code block prior to the return statement.

like image 170
Sergey Kalinichenko Avatar answered Sep 28 '22 08:09

Sergey Kalinichenko


Here is another sample:

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

Or by StreamEx:

StreamEx.split(fruitString, ", ")
        .map(s -> StreamEx.split(s, " ").map(String::toUpperCase).joining("_"))
        .map(Fruit::valueOf).toList();
like image 41
123-xyz Avatar answered Sep 28 '22 07:09

123-xyz


Your Enum

static enum Fruit {
    RED_APPLE, BLUE_BANANA, ORANGE
}

Main code:

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 method to offload dirty mapping part

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());
}
like image 28
jmj Avatar answered Sep 28 '22 06:09

jmj