我被困在一个练习中,我应该在其中创建一个方法来检查 map 的值是否在开头具有特定的数字链。
该项目必须有 3 个类:Obywatele(公民)、RejestrObywateli(公民登记)和 Main。 Obywatele(公民)类需要具有 3 个字符串属性(pesel、name、surname)。属性 pesel
是一个数字(波兰公民的 ID)。 “pesel”中的前两个数字表示公民的出生年份。
例如对于一个 pesel 96060501514,出生年份是 1996。
我应该在类 RejestrObywateli 中编写一个方法,它可以找到所有 90 年代之前出生的公民并将它们打印出来。
由于 private String pesel
是一个字符串,我试图将它解析为一个整数,但不知道下一步该怎么做。
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Obywatel {
private String pesel;
private String imie; // name
private String nazwisko; //surname
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RejestrObywateli {
private Map<String, Obywatel> mapa = new HashMap<>();
public void dodajObywatela(Obywatel o) {
mapa.put(o.getPesel(), o);
}
最佳答案
首先:
private Map<Obywatel, String> mapa = new HashMap<Obywatel, String>();
我不认为这种结构在未来会有帮助。
任何!回答你的问题:
I am supposed to write a method in the class RejestrObywateli which finds all the citizens that are born before the 90s and prints them out.
如果你只想获取 map 的键(Obywatel
)那么你可以使用:
List<Obywatel> collect = mapa.entrySet().stream()
.filter(c -> Integer.valueOf(c.getValue().substring(0, 2)) < 90)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
否则如果你想获取值(String
)你可以使用:
List<String> collect = mapa.entrySet().stream()
.filter(c -> Integer.valueOf(c.getValue().substring(0, 2)) < 90)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
或者如果你想打印键和值:
mapa.entrySet().stream()
.filter(c -> Integer.valueOf(c.getValue().substring(0, 2)) < 90)
.forEach(entry -> System.out.println(String.format("k = %s, v = %s", entry.getKey(), entry.getValue())));
关于java - 如何在以特定数字开头的 map 中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56445046/