Organized information on various data transformations in Java.
Use parseInt and parseDouble methods to convert strings to numbers.
public class ParseInt {
public static void main(String[] args) {
int x = Integer.parse
```java
int x = Integer.parseInt("12");
double c = Double.parseDouble("12");
int b = Integer.parseInt("100", 2);
System.out.println(x); // 12
System.out.println(c); // 12.0
System.out.println(b); // 4
System.out.println(Integer.parseInt("101", 8)); // 65
}
}
Output:
12
12.0
4
65
Convert date strings to Date objects using SimpleDateFormat and ParsePosition.
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LocaleDateFormat {
public static void main(String[] args) {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf1.parse("10/14/2020");
System.out.println(date1); // Wed Oct 14 00:00:00 EEST 2020
Date date2 = sdf2.parse("14/10/2020");
System.out.println(date2); // Wed Oct 14 00:00:00 EEST 2020
String myString = "here is the date: 14/10/2020";
ParsePosition p1 = new ParsePosition(18);
Date date3 = sdf2.parse(myString, p1);
System.out.println(date3); // Wed Oct 14 00:00:00 EEST 2020
}
}
Output:
Wed Oct 14 00:00:00 EEST 2020
Wed Oct 14 00:00:00 EEST 2020
Wed Oct 14 00:00:00 EEST 2020
Convert an object to a Data Transfer Object (DTO) using BeanUtils.
import org.springframework.beans.BeanUtils;
public class DTOConverter {
public static DataDto objectToDataDto(Object dtoObject) {
DataDto dataDto = new DataDto();
BeanUtils.copyProperties(dtoObject, dataDto);
return dataDto;
}
}
Use MapStruct for converting an entity to a DTO.
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
@Mapping(source = "numberOfSeats", target = "seatCount")
CarDto carToCarDto(Car car);
}