我即将从字符串创建二维数组:
char[][] chars;
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Run Code Online (Sandbox Code Playgroud)
但是我怎么能用Java 8 Streams做到这一点,因为我不想通过休闲循环来做到这一点?
我有以下代码:
public boolean foo(List<JSONObject> source, String bar, String baz) {
List<String> myList = newArrayList();
source.forEach(json -> {
if (!(json.get(bar) instanceof JSONObject)) {
myList.add(json.get(bar).toString());
} else {
myList.add(json.getJSONObject(attribute).get("key").toString());
}
});
/**
* do something with myList and baz
*/
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否有办法if-else使用过滤器进行内联条件.
有点像:
List<String> myList = source.stream()
.filter(json -> !(json.get(bar) instanceof JSONObject))
.map(item -> item.get(attribute).toString())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
如果我按照上面的方法进行,我将错过应该是"其他"的条件.如何使用更多java-8方式实现我想要的目标?
提前致谢!
我最近开始使用collectAndThen,发现与其他编码程序相比,它需要花费相当长的时间,我用它来执行类似的任务.
这是我的代码:
System.out.println("CollectingAndThen");
Long t = System.currentTimeMillis();
String personWithMaxAge = persons.stream()
.collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getAge)),
(Optional<Person> p) -> p.isPresent() ? p.get().getName() : "none"
));
System.out.println("personWithMaxAge - "+personWithMaxAge + " time taken = "+(System.currentTimeMillis() - t));
Long t2 = System.currentTimeMillis();
String personWithMaxAge2 = persons.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.findFirst().get().name;
System.out.println("personWithMaxAge2 : "+personWithMaxAge2+ " time taken = "+(System.currentTimeMillis() - t2));
Run Code Online (Sandbox Code Playgroud)
在这里输出:
CollectingAndThen
personWithMaxAge - Peter time taken = 17
personWithMaxAge2 : Peter time taken = 1
Run Code Online (Sandbox Code Playgroud)
这表明收集和收集时间相对较长.
所以我的问题是 - 我应该继续收集和其他建议吗?
我有这段代码,我想返回一个postCodes列表:
List<String> postcodes = new ArrayList<>();
List<Entry> entries = x.getEntry(); //getEntry() returns a list of Entry class
for (Entry entry : entries) {
if (entry != null) {
Properties properties = entry.getContent().getProperties();
postcodes.addAll(Arrays.asList(properties.getPostcodes().split(",")));
}
}
return postcodes;
Run Code Online (Sandbox Code Playgroud)
这是我尝试使用stream()方法和以下链式方法:
...some other block of code
List<Entry> entries = x.getEntry.stream()
.filter(entry -> recordEntry != null)
.flatMap(entry -> {
Properties properties = recordEntry.getContent().getProperties();
postCodes.addAll(Arrays.asList(properties.getPostcodes().split(",")));
});
Run Code Online (Sandbox Code Playgroud) 我试图从.stream()via 2 打印值.filter().但价值不是印刷.
一个人.filter()能够打印值.
请在下面找到我的代码.
listProducts.stream()
.flatMap(listproducts -> listproducts.getProductAttr().stream())
.flatMap(attr ->attr.getProductAttrValue().stream())
.filter(av -> av.getLabel().equalsIgnoreCase("source"))
.filter(av -> av.getLabel().equalsIgnoreCase("description"))
.forEachOrdered(av -> System.out.println(av.getValue()));
Run Code Online (Sandbox Code Playgroud) 我正在迭代Hashmap列表,使用以下代码查找所需的HashMap对象.
public static Map<String, String> extractMap(List<Map<String, String>> mapList, String currentIp) {
for (Map<String, String> asd : mapList) {
if (asd.get("ip").equals(currentIp)) {
return asd;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我在考虑使用Java 8流.这是我用来显示所需对象的代码.
public static void displayRequiredMapFromList(List<Map<String, String>> mapList, String currentIp) {
mapList.stream().filter(e -> e.get("ip").equals(currentIp)).forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)
我无法使用以下代码从流中获取所需的Map
public static Map<String, String> extractMapByStream(List<Map<String, String>> mapList, String currentIp) {
return mapList.stream().filter(e -> e.get("ip").equals(currentIp))
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
}
Run Code Online (Sandbox Code Playgroud)
这会导致语法错误类型不匹配:无法从Map转换为Map.我有什么需要放在这里获取地图?
关于函数式编程,特别是新的Java 8流API,有太多的炒作.它被宣传为旧的良好循环和命令式范例的良好替代品.事实上,有时它看起来很不错并且做得很好.但性能呢?
例如,这是关于此的好文章:Java 8:没有更多循环 使用循环,您可以通过一次迭代完成所有工作.但是使用新的流API,您将链接多个循环,这使得它更慢(是不是?).看看他们的第一个样本.在大多数情况下,Loop甚至不会遍历整个阵列.但是,要使用新的流API进行过滤,您必须遍历整个数组以过滤掉所有候选项,然后您将能够获得第一个.
在这篇文章中提到了一些懒惰:
我们首先使用filter操作来查找具有Java标记的所有文章,然后使用findFirst()操作来获取第一个匹配项.由于流是惰性的并且过滤器返回流,因此该方法仅处理元素,直到找到第一个匹配.
作者对这种懒惰的意思是什么?
我做了简单的测试,它表明旧的良好循环解决方案可以快速运行10倍然后流式处理.
public void test() {
List<String> list = Arrays.asList(
"First string",
"Second string",
"Third string",
"Good string",
"Another",
"Best",
"Super string",
"Light",
"Better",
"For string",
"Not string",
"Great",
"Super change",
"Very nice",
"Super cool",
"Nice",
"Very good",
"Not yet string",
"Let's do the string",
"First string",
"Low string",
"Big bunny",
"Superstar",
"Last");
long start = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
getFirstByLoop(list);
}
long end = …Run Code Online (Sandbox Code Playgroud) 场景:我需要List使用Java 8流API基于某些字段条件为对象设置一些值.
以下是对象的示例User.
public class User{
private int id;
private String name;
private String text;
private boolean isActive;
}
Run Code Online (Sandbox Code Playgroud)
这是我编写的代码
List<User> users = userDao.getAllByCompanyId(companyId);
users.stream()
.filter(Objects::nonNull)
.filter(User::isActive)
.peek(user -> user.setText('ABC'))
.filter(user -> !user.isActive())
.peek(user -> user.setText('XYZ')
Run Code Online (Sandbox Code Playgroud)
我知道我根据条件将值设置为object的方式是错误的.
这只是一个使用流的试用版,最后我需要将值设置为usersobject.
有没有办法处理if-else条件.
我有以下服务正常使用 Java8
List<ReportCount> getReportDetails(List<String> statusList);
statusList.add(Arrays.asList("SUCCESS"));
statusList.add(Arrays.asList("CANCELLED"));
statusList.add(Arrays.asList("ON_HOLD","INPROGRESS"));
statusList.stream()
.map(reportService::getReportDetails)
.forEach(e -> reportMap.put("report_" + reportMap.size(), e));
Run Code Online (Sandbox Code Playgroud)
如何使用上面的代码为下面的方法传递1个参数.
String id="CA";
List<ReportCount> getReportDetails(List<String> statusList, String id);
Run Code Online (Sandbox Code Playgroud)
有谁可以帮忙.谢谢
我有这段代码,从具有某些条件的DeviceEvents列表中提取
List<DeviceEvent> deviceEvents = new ArrayList<>();
deviceEventService
.findAll(loggedInUser())
.filter(this::isAlarmMessage)
.iterator()
.forEachRemaining(deviceEvents::add);
private boolean isAlarmMessage (DeviceEvent deviceEvent) {
return AlarmLevelEnum.HIGH == deviceEvent.getDeviceMessage().getLevel();
}
Run Code Online (Sandbox Code Playgroud)
但我得到了这个编译错误:
The method filter(this::isAlarmMessage) is undefined for the type
Iterable<DeviceEvent>
Run Code Online (Sandbox Code Playgroud)
findAll 返回一个 Iterable<DeviceEvent> java-stream ×10
java ×9
java-8 ×9
lambda ×3
collections ×2
arrays ×1
chars ×1
collect ×1
collectors ×1
filtering ×1
flatmap ×1
hashmap ×1
list ×1
performance ×1