Home > Blockchain >  How to read data set without line break in java
How to read data set without line break in java

Time:09-22

I have a dataset like the following,

chris~88~alex~23~nivya~34~simon~33...........

this data represents the name and the age of some people. How I can capture each of their name and age into a pojo and save in DB. I need to know how we can use stringutils to get their name and age out of this large string.

CodePudding user response:

You can do it simply by using split method from String class. Split by character ~, which will return array of string. Where even index values will be name and odd number values will be age. Then you can map that to object of pojo class and create list.

Code to convert String to POJO of name and age:

public static void main(String[] args) {
    String a = "chris~88~alex~23~nivya~34~simon~33";
    String[] nameAge = a.split("~");

    List<Person> persons = IntStream.range(0, nameAge.length).filter(x -> x % 2 == 0)
        .mapToObj(i -> new Person(nameAge[i], Integer.valueOf(nameAge[i   1]))).collect(Collectors.toList());

    System.out.println(persons);
  }

POJO :

class Person {

  String name;

  int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  @Override
  public String toString() {
    return "Person [name="   name   ", age="   age   "]";
  }
}

CodePudding user response:

I don't know what specific DB you are using, but here is a possible way to split the dataset with a regex:

String dataset = "chris~88~alex~23~nivya~34~simon~33~tim~34~berta~12~jon~55";
String[] splitDataset = dataset.split("~");

splitDataset now contains for all even the i the name and for all uneven indices the respective age (i 1).

  • Related