我正在尝试使用`stream将以下代码重构为lambda表达式,尤其是嵌套的foreach循环:
public static Result match (Response rsp) {
Exception lastex = null;
for (FirstNode firstNode : rsp.getFirstNodes()) {
for (SndNode sndNode : firstNode.getSndNodes()) {
try {
if (sndNode.isValid())
return parse(sndNode); //return the first match, retry if fails with ParseException
} catch (ParseException e) {
lastex = e;
}
}
}
//throw the exception if all elements failed
if (lastex != null) {
throw lastex;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我开始时:
rsp.getFirstNodes().forEach().?? // how to iterate the nested 2ndNodes?
Run Code Online (Sandbox Code Playgroud) Parent是Child继承的类.这是由GrandChild继承的.每个类都包含子类的List(即Parent包含Child和Child的List包含GrandChild的List).每个类包含50个属性(attrib1-atrib50).getChildList()返回类型为Child的对象的arrayList getGrandChildList()返回GrandChild类型的对象的arrayList
设resultSet为Parent列表
List<Parent> resultSet
Run Code Online (Sandbox Code Playgroud)
现在我想根据一些属性对列表进行排序.例如,如果我想基于两个父属性(比如属性1和属性2)对resultSet进行排序,我使用此代码.
Comparator<Parent> byFirst = (e1, e2) -> e2.getAttrib1().compareTo(e1.getAttrib1());
Comparator<Parent> bySecond = (e1, e2) -> e1.getAttrib2().compareTo(e2.getAttrib2());
Comparator<Parent> byThird = byFirst.thenComparing(bySecond);
List<Parent> sortedList = resultSet.stream().sorted(byThird).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
现在我想根据Child类的属性1和GrandChild类的属性1对父列表进行排序.我应该如何排序呢.
我第一次尝试使用java 8流...
我有一个对象Bid,它代表用户对拍卖中项目的出价.我有一个出价列表,我想制作一张地图,其中包含用户出价的拍卖数量(不同).
这是我的看法:
bids.stream()
.collect(
Collectors.groupingBy(
bid -> Bid::getBidderUserId,
mapping(Bid::getAuctionId, Collectors.toSet())
)
).entrySet().stream().collect(Collectors.toMap(
e-> e.getKey(),e -> e.getValue().size())
);
Run Code Online (Sandbox Code Playgroud)
它工作,但我觉得我在作弊,因为我流式传输地图的入口集,而不是在初始流上进行操作...必须是一个更正确的方式这样做,但我无法想象出来...
谢谢
我设法解析String一个LocalDate对象:
DateTimeFormatter f1=DateTimeFormatter.ofPattern("dd MM yyyy");
LocalDate d=LocalDate.parse("26 08 1984",f1);
System.out.println(d); //prints "1984-08-26"
Run Code Online (Sandbox Code Playgroud)
但我不能这样做LocalTime.这段代码:
DateTimeFormatter f2=DateTimeFormatter.ofPattern("hh mm");
LocalTime t=LocalTime.parse("11 08",f2); //exception here
System.out.println(t);
Run Code Online (Sandbox Code Playgroud)
抛出一个DateTimeParseException:
Exception in thread "main" java.time.format.DateTimeParseException: Text '11 08' could not be parsed: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=8, HourOfAmPm=11},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalTime.parse(Unknown Source)
at com.mui.cert.Main.<init>(Main.java:21)
at com.mui.cert.Main.main(Main.java:12)
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=8, HourOfAmPm=11},ISO of type …Run Code Online (Sandbox Code Playgroud) 在我们在Jdk 8上运行的应用程序中,我们使用VisualVM来跟踪加载类的使用情况和元空间的使用情况.
在我们的应用程序运行的某个时间点,我们看到加载的类的数量不再增加,但是在我们的程序运行时,元空间的大小仍然增加.那么除了类之外还有哪些东西存储在元空间中,这可能会导致这种情况呢?
每当我必须检查方法的给定参数是否为空时,我曾经写过一个空检查并抛出一个IllegalArgumentException如果null检查失败:
if (user == null) {
throw new IllegalArgumentException("User can't be null.");
}
Run Code Online (Sandbox Code Playgroud)
但是,通过阅读某些Java 8类的源代码ArrayList,我发现Oracle正在使用Objects.requireNonNull针对空值检查参数,然后,如果测试失败,NullPointerException则抛出a.
这样,早期的代码片段应该采用这种方法:
Objects.requireNonNull(user, "User can't be null.");
Run Code Online (Sandbox Code Playgroud)
更小,更易读.
假设我已经控制了系统的整个异常处理,(即使我不应该,有时它是业务的一部分来处理这些未经检查的异常),我应该替换我IllegalArgumentException的NullPointerException并使用Objects.requireNonNull而不是编写我自己的null检查抛出异常?
在我目前的工作中,我们将一些代码重写为Java 8.如果你有这样的代码:
if(getApi() != null && getApi().getUser() != null
&& getApi().getUser().getCurrentTask() != null)
{
getApi().getUser().getCurrentTask().pause();
}
Run Code Online (Sandbox Code Playgroud)
你可以简单地重写它
Optional.ofNullable(this.getApi())
.map(Api::getUser)
.map(User::getCurrentTask)
.ifPresent(Task::pause);
Run Code Online (Sandbox Code Playgroud)
不改变代码行为.但是,如果中间的东西可以抛出NPE,因为它没有被检查为空呢?
例如:
if(getApi() != null && getApi().getUser() != null
&& getApi().hasTasks())
{
getApi().getMasterUser(getApi().getUser()) //<- npe can be here
.getCurrentTask().pause();
}
Run Code Online (Sandbox Code Playgroud)
使用optionals重写这样的代码的最佳方法是什么?(它应该完全相同,并在getMasterUser(...)返回null 时抛出npe )
UPD 第二个例子:
if(getApi()!=null && getApi.getUser() != null)
{
if(getApi().getUser().getDepartment().getBoss() != null)// <- nre if department is null
{
getApi().getUser().getDepartment().getBoss().somefunc();
}
}
Run Code Online (Sandbox Code Playgroud)
它有api,用户,老板的零检查,但不是部门.怎么用选项?
我是仿制药的新手.你可以看到,我知道的确切类型后重复一些代码val,filterSmall,filterGreat.我想编写用于val与过滤器值进行比较的通用代码.我可以写这样的东西
private <T> boolean compareAgainstFilters(T val, T filterSmall, T filterGreat) {
if (!(filterSmall != null && filterSmall <= val)) {
return true;
}
if (!(filterGreat != null && val <= filterGreat)) {
return true;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
但是在编译时,java不知道<=运算符是否对类型有效T.
我不想重复代码,那么我怎么能实现呢?
if (value != null) {
switch (value.getClass().getName()) {
case "java.lang.Long":
Long filterSmall = (Long) filterSmaller;
Long filterGreat = (Long) filterGreater;
Long val = (Long) value;
if (!(filterSmall != …Run Code Online (Sandbox Code Playgroud) 我正在尝试将for循环转换为功能代码.我需要向前看一个值,并且还要看一个值.是否可以使用流?以下代码是将罗马文本转换为数值.不确定带有两个/三个参数的reduce方法是否有帮助.
int previousCharValue = 0;
int total = 0;
for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
RomanNumeral romanNum = RomanNumeral.valueOf(Character.toString(current));
if (previousCharValue > 0) {
total += (romanNum.getNumericValue() - previousCharValue);
previousCharValue = 0;
} else {
if (i < input.length() - 1) {
char next = input.charAt(i + 1);
RomanNumeral nextNum = RomanNumeral.valueOf(Character.toString(next));
if (romanNum.getNumericValue() < nextNum.getNumericValue()) {
previousCharValue = romanNum.getNumericValue();
}
}
if (previousCharValue == 0) {
total += romanNum.getNumericValue();
}
} …Run Code Online (Sandbox Code Playgroud) 是否可以从中创建流com.fasterxml.jackson.databind.node.ArrayNode?
我试过了:
ArrayNode files = (ArrayNode) json.get("files");
Stream<JsonNode> stream = Stream.of(files);
Run Code Online (Sandbox Code Playgroud)
但它实际上会给出一个元素的流,即初始的ArrayNode对象.
应该是正确的结果Stream<JsonNode>,我可以实现吗?
java-8 ×10
java ×8
java-stream ×4
comparator ×1
date-parsing ×1
exception ×1
fasterxml ×1
generics ×1
jackson ×1
jvm ×1
lambda ×1
metaspace ×1
optional ×1
sorting ×1