java - 需要使用 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]
解决方案
如果您只对打印 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 列表。
推荐阅读
- c# - C# 排序列表视图
- python - Python 清晰的线条怪异的音符字符
- javascript - 如何将代码从 rxjs v5 转换为 rxjs v6 以进行 catch?
- vba - 如果使用 VBA 填充表格,则不会在以下页面上自动重复标题行
- android - Android : [INSTALL_FAILED_NO_MATCHING_ABIS: 无法提取本机库,res=-113]
- python - 优化 tensorflow 数据集 api 中的 shuffle 缓冲区大小
- php - MYSQL 5.6 和 8.0 utf8mb4:PHP 5.6 utf8
- c++ - C++ 项目的 ECLIPSE makefile -- 源目录
- python - 如何格式化我的数据以在 Keras 上进行训练和测试
- node.js - 如何使用 Mongo 在 express 中传递对象元素?