I want to print the last digit from a string using a lambda expression. Using the below code I was able to print a complete number I but want to print the last digit
public static void main(String[] args) {
List<TestDTO> studs = new ArrayList<>();
studs.add(new TestDTO("101", "Test 101"));
studs.add(new TestDTO("102", "Test 102"));
Map<String, TestDTO> mapDbCardDtl = studs.stream().collect(Collectors.toMap(TestDTO::getId, Function.identity()));
Set<String> s = mapDbCardDtl.keySet();
System.out.println("s: " + s.toString());
}
Below is the DTO
public class TestDTO {
String id;
String name;
public TestDTO(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Output from the above code:
s: [101, 102]
The expected output:
S : [1, 2]
You can't use Funcion#identity and expect to have different entity with modified values. One way is to convert Map<String, TestDTO> to Map<String, String> and use the following code:
Map<String, String> mapDbCardDtl = studs
.stream()
.collect(Collectors.toMap(TestDTO::getId,
(testDto) -> String.valueOf(testDto.getId().charAt(testDto.getId().length() - 1))));
Set<String> s = mapDbCardDtl.keySet();
System.out.println("s: " + s.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With