首页 > 解决方案 > 需要使用 java 的 lamda 表达式打印字符串的最后一位

问题描述

想要使用 lamda 表达式从字符串中打印最后一个数字。使用下面的代码能够打印完整的数字,但想打印最后一位

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());
    }

下面是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;
    }

}

从上面的代码得到的输出

s: [101, 102]

预期产出

S : [1, 2]

标签: java

解决方案


如果您只对打印 id 中的最后一个数字感兴趣,这是一个写为 String 的数字,那么:

 List<String> s = studs.stream()
            .map(dto->dto.getId())
            .map(id -> String.valueOf(id.charAt(id.length() - 1))) // take last character and cast to String
            .collect(Collectors.toList()); 

如果你想得到。名称值的最后一位数字:

 final Pattern numberPattern = Pattern.compile(".*([0-9]+).*$");
 List<String> s = studs.stream()
            // find nunmber in name
            .map(dto -> numberPattern.matcher(dto.getName()))
            .filter(Matcher::matches)
            .map(matcher -> matcher.group(1))
             // find last digit
            .map(lastNumber ->String.valueOf(lastNumber.charAt(lastNumber.length()-1)))
            .collect(Collectors.toList());

小费:

如果您想mapDbCardDtl将最后一位数字作为密钥,那么当多个数字以相同数字结尾时,您可能会失败。您将不得不在 toMap 收集器中使用覆盖合并功能。

public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction)

第二种解决方案是使用 groupBy 方法,它将 TestDTO 聚合到Map<String,List< TestDTO >>. 这里的关键是你的数字和价值:这个数字的 Dto 列表。


推荐阅读