List<String> listA = new Arraylist();
List<String> listB = new Arraylist();
Run Code Online (Sandbox Code Playgroud)
鉴于以上2个列表,我想迭代并在每个元素上调用相同的方法.
选项1
for(String aStr: listA){
someCommonMethodToCall(aStr);
someCommonMethodToCall(aStr);
...
}
for(String bStr: listB){
someCommonMethodToCall(bStr);
someCommonMethodToCall(bStr);
...
}
Run Code Online (Sandbox Code Playgroud)
要么
选项2
List<String> mergedList = new ArrayList();
mergedList.addAll(listA);
mergedList.addAll(listB);
for(String elem: mergedList){
someCommonMethodToCall(elem);
someCommonMethodToCall(elem);
...
}
Run Code Online (Sandbox Code Playgroud)
要么
选项3
我认为选项1应该是最好的.是否有一些Java 8 lambda方法可以做到这一点?此外,性能方面,还有什么比选项1更好?
请考虑以下代码.我读到在处理Stream API时在代码中实现不变性非常重要.我们怎样才能获得具有不变性的小写项目列表?
List<String> stockList = Arrays.asList("GOOG", "AAPL", "MSFT", "INTC");
List<String> stockList2 = new ArrayList<>();
stockList.parallelStream()
.filter(e -> !e.contains("M"))
.map(String::toLowerCase)
.map(e -> stockList2.add(e))
.collect(toList());
stockList2.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud) 我试图理解CompletableFuture,并遇到了2个方法,然后是ApplyAsync然后是Make.我试图了解这两者之间的区别.
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " Printing hello");
return "Hello";
}).thenCompose((String s) -> {
return CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " Adding abc");
return "abc "+s;});
}).thenApplyAsync((String s) -> {
System.out.println(Thread.currentThread().getName() + " Adding world");
return s + " World";
}).thenApplyAsync((String s) -> {
System.out.println(Thread.currentThread().getName() + " Adding name");
if (false) {
throw new RuntimeException("Oh no exception");
}
return s + " player!";
}).handle((String s, Throwable t) -> {
System.out.println(s != null ? s : "BLANK"); …Run Code Online (Sandbox Code Playgroud) 希望有人能帮助我.我有ArrayList一Invoice堂课.我想要得到的是过滤这个ArrayList并找到其中一个属性与a匹配的第一个元素regex.这个Invoice类看起来像这样:
public class Invoice {
private final SimpleStringProperty docNum;
private final SimpleStringProperty orderNum;
public Invoice{
this.docNum = new SimpleStringProperty();
this.orderNum = new SimpleStringProperty();
}
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我正在使用它regex (\\D+)进行过滤,以便查找orderNum属性中是否存在任何不具有整数格式的值.所以基本上我正在使用这个流
Optional<Invoice> invoice = list
.stream()
.filter(line -> line.getOrderNum())
.matches("(\\D+)"))
.findFirst();
Run Code Online (Sandbox Code Playgroud)
但它不起作用.任何的想法?我一直在寻找,我发现如何使用pattern.asPredicate()像这样:
Pattern pattern = Pattern.compile("...");
List<String> matching = list.stream()
.filter(pattern.asPredicate())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
随着List的Integer,String等等,但我还没有找到如何与做POJO.任何帮助都感激不尽.美好的一天
我正在尝试使用Java 8 Stream API 将ArrayList包含的float值转换为原始浮点数组.到目前为止我尝试的是这样的:
List<Float> floatList = new ArrayList<Float>();
float[] floatArray = floatList.stream().map(i -> i).toArray(float[]::new)
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(Mailingadresse.class).getPropertyDescriptors();
Map<String, PropertyDescriptor> m = Arrays
.stream(propertyDescriptors)
.filter(pd -> pd.getReadMethod() != null)
.collect(Collectors.toMap(pd -> pd.getName().toLowerCase(), Function::identity));
Run Code Online (Sandbox Code Playgroud)
Eclipse显示
收集器类型中的Map(Function,Function)方法不适用于参数((pd) - > {},Function :: identity)
为什么是这样?
我有一个HashMap,我需要按值排序,我试图保持简洁,所以我使用Java 8.但是各种方法都不起作用,我不确定为什么.我试过这个:
followLikeCount.values()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
这会抛出这个编译时异常:
Main.java:65: error: no suitable method found for sorted(Comparator<Entry<Object,V#1>>)
.sorted(Map.Entry.comparingByValue())
Run Code Online (Sandbox Code Playgroud)
我不明白为什么观察不匹配.我也尝试过使用比较器:
Comparator<Map.Entry<Integer, Integer>> byValue =
Map.Entry.<Integer, Integer>comparingByValue();
Run Code Online (Sandbox Code Playgroud)
这会产生类似的错误.请问您能告知为什么比较器无效?
java 8中的Predicate接口有一个静态方法,如:
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
Run Code Online (Sandbox Code Playgroud)
为什么不这样做:
return (null == targetRef)
? null
: object -> targetRef.equals(object);
Run Code Online (Sandbox Code Playgroud)
我的意思是,这个方法参考Objects::isNull没有带来任何进一步的改进......并且正在减少一点可读性......
if为null我返回true ...完成!或者我在幕后错过了一些陷阱......?
假设我有一个名为Student的对象列表.对象学生的定义是这样的
public Class Student {
private String studentName;
private String courseTaking;
}
Run Code Online (Sandbox Code Playgroud)
在学生列表中,可以有多个学生对象具有相同的studentName但不同的courseTaking.现在我想将学生列表转换为studentName和courseTaking的地图
Map<String, Set<String>>
Run Code Online (Sandbox Code Playgroud)
关键是studentName,并且该值是同一个学生作为一组放在一起的所有课程.我怎么能用stream()和collect()做到这一点?
我必须使用Streams API从给定文件中找到所有最长的单词.我做了它在几个步骤,但寻找一些"一个班轮",其实我处理整个文件两次,第一次找字和第二的最大长度为所有比较的最大长度,假设它不是最好的表现; P有人能帮帮我吗?看看代码:
public class Test {
public static void main(String[] args) throws IOException {
List<String> words = Files.readAllLines(Paths.get("alice.txt"));
OptionalInt longestWordLength = words.stream().mapToInt(String::length).max();
Map<Integer, List<String>> groupedByLength = words.stream().collect(Collectors.groupingBy(String::length));
List<String> result = groupedByLength.get(longestWordLength.getAsInt());
}
}
Run Code Online (Sandbox Code Playgroud)
我想直截了当:
List<String> words = Files.readAllLines(Paths.get("alice.txt"));
List<String> result = // code
Run Code Online (Sandbox Code Playgroud)
文件每行只包含一个单词,无论如何它并不重要 - 问题是关于正确的流代码.
java ×10
java-8 ×10
java-stream ×5
arraylist ×1
arrays ×1
dictionary ×1
immutability ×1
lambda ×1
loops ×1
methods ×1
pojo ×1
predicate ×1
regex ×1