Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to print last digit of string using lambda expression using java

Tags:

java

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]
like image 603
Shiladittya Chakraborty Avatar asked Jan 31 '26 03:01

Shiladittya Chakraborty


1 Answers

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());
like image 158
Shababb Karim Avatar answered Feb 02 '26 17:02

Shababb Karim