Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

Java 8 Convert Object to String separated by VALUE

I'm trying to conver a java Object to a string separated by "SEPARATOR".

Example

public class Person{

int id;
String name;
String age;
String sex;
}

Main method

Person per = new Person(1, "Kevin", "20", "Male");
String objectAsText = per.ConvertObjectToString(per, "|");

Expected output

1|Kevin|20|Male

Note that the java object is not a list. And I also want to add a validation so the method ConvertObjectToString can avoid printing object values that are null. ie

Person per = new Person(1, "Kevin", "Male");
String objectAsText = per.ConvertObjectToString(per, "|");

Expected output

1|Kevin|Male

I know that this can be achieved using toString method, but I want to know if there is any other efficient way. Also I don't want to check value by value if null since the java object can be large.

question from:https://stackoverflow.com/questions/65601956/java-8-convert-object-to-string-separated-by-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't want to check each value, I would recommend java object converting into JSON, like into Map<String,Object> and then use Collectors.joining

String value = map.values()
            .stream().filter(Objects::nonNull)
            .map(Object::toString)
            .collect(Collectors.joining("|"));

You can do it using the reflection package, but make sure your fields are public

 Person per = new Person(1, "Kevin", "20", "Male");

   String value = Arrays.stream(Person.getClass().getFields())
           .map(f-> {
               try {
                   return f.get(per).toString();
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               }
               return null;
           }).filter(Objects::nonNull).collect(Collectors.joining("|"));

    System.out.println(value); //1|Kevin|20|Male

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...