Java convert a string to list of enums

This question already has an answer here:

  • Lookup Java enum by string value 23 answers

  • Your question doesn't really make much sense. If you want to send or store list of enums then you can simply serialize and deserialize it since ArrayList and each enum are Serializable .

    Example:

    List<Day> ofiginalList = new ArrayList<Day>();
    ofiginalList.add(Day.Monday);
    ofiginalList.add(Day.Tuesday);
    
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    
    ObjectOutput out = new ObjectOutputStream(bout);
    out.writeObject(ofiginalList);
    
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInput in = new ObjectInputStream(bin);
    
    List<Day> deserializedList = (List<Day>) in.readObject();
    System.out.println(deserializedList);
    

    Output: [Monday, Tuesday] .


    In case you use Java 8:

    //assume your Day enum has more values
    String string = "[Monday, Wednesday, Tuesday, Friday, Thursday]";
    String stringWithNoBrackets = string.substring(1, string.length() - 1);
    List<Days> days = Arrays.asList(stringWithNoBrackets.split(",s+"))
            .stream()
            .map(Days::valueOf)
            .collect(Collectors.toList());
    System.out.println(days);
    

    Also, we don't need to convert the array into a list, using less code:

    List<Days> days2 = Arrays.stream(stringWithNoBrackets.split(",s+"))
        .map(Days::valueOf)
        .collect(Collectors.toList());
    

    你可以尝试做类似的事情

    List<Day> days = new ArrayList<>();
    StringTokenizer tokenizer = new StringTokenizer("[Monday, Tuesday]", "[], ");
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      days.add(Day.valueOf(Day.class, token));
    }
    
    链接地址: http://www.djcxy.com/p/38086.html

    上一篇: 通过命令行访问枚举

    下一篇: Java将一个字符串转换为枚举列表