Java将一个字符串转换为枚举列表
这个问题在这里已经有了答案:
你的问题并没有多大意义。 如果你想发送或存储枚举列表,那么你可以简单地序列化和反序列化它,因为ArrayList
和每个enum
都是可Serializable
。
例:
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);
输出: [Monday, Tuesday]
。
如果你使用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);
另外,我们不需要使用较少的代码将数组转换为列表:
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/38085.html