我有一个公司实体对象列表。
package com.raghu.example2;
public class CompanyEntity {
private String name;
private String locationName;
private String officeName;
private String buildingName;
public CompanyEntity(String name, String locationName, String officeName, String buildingName) {
super();
this.name = name;
this.locationName = locationName;
this.officeName = officeName;
this.buildingName = buildingName;
// System.out.println(this);
}
public String getName() {
return name;
}
public String getLocationName() {
return locationName;
}
public String getOfficeName() {
return officeName;
}
public String getBuildingName() {
return buildingName;
}
@Override
public String toString() {
StringBuilder builder …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习Lambda表达式,
interface MathOperartor 我已经确定使用Lambda表达式可以做到的操作()重载了,我确实可以使用Lambda表达式,但似乎无法弄清楚这里的问题是什么:
public static void main(String[] args) {
LambdaLearning lb = new LambdaLearning();
MathOperartor add = (a , b )-> a + b; // error: The target type of this expression must be a functional interface
MathOperartor sub = (a , b) -> a - b; // same error
MathOperartor mul = (a , b) -> a * b; // ''
MathOperartor div = (a , b) -> a / b; // ''
System.out.println(lb.operate(10, 15, add));
System.out.println(lb.operate(10.5f, 15.5f, …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个过滤谓词,它将根据不同对象中保存的值过滤列表,但是我想要提取要比较的值的对象在执行比较时可用,而不是在定义谓词的时间.
这是一个SSCCE
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class StreamTest {
public static void main(String [] args){
DataContainer dc = new DataContainer();
Predicate<Integer> p = new Predicate<Integer>(){
@Override
public boolean test(Integer t) {
/********************************************/
return t > 6; // I need this to be t > the limitValue that is available when the predicate gets executed
/********************************************/
}
};
System.out.println(dc.numberOfValuesGreaterThan(p, new LimitValue(6)));
}
}
class DataContainer{
private List<Integer> l = Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10});
public long numberOfValuesSatisfyingPredicate(Predicate predicate,LimitValue lv){
return l.stream() …Run Code Online (Sandbox Code Playgroud) 我在" Java SE 8 for the Really Impatient:Programming with Lambdas "中进行了一个例子.
让我们看一个简单的例子.假设您记录一个事件:
Run Code Online (Sandbox Code Playgroud)logger.info("x: " + x + ", y: " + y);如果将日志级别设置为禁止INFO消息会发生什么?计算消息字符串并将其传递给info方法,然后该方法决定将其丢弃.如果字符串连接仅在必要时发生,那不是更好吗?
仅在必要时运行代码是lambda的用例.标准习惯用法是将代码包装在无参数lambda中:
Run Code Online (Sandbox Code Playgroud)() -> "x: " + x + ", y: " + y以下方法提供了延迟日志记录:
Run Code Online (Sandbox Code Playgroud)public static void info(Logger logger, Supplier<String> message) { if (logger.isLoggable(Level.INFO)) logger.info(message.get()); }我们使用类的
isLoggable方法Logger来决定是否应该记录INFO消息.如果是这样,我们通过调用它的抽象方法调用lambda,该方法恰好称为get.
所以我不明白的是 - 我们可以使用logger.isLoggable(Level.INFO)示例1中的代码(不使用lambdas的代码),只有logger.isLoggable(Level.INFO)满足时才会计算消息字符串.
logger.info("x: " + x + ", y: " + y);
Run Code Online (Sandbox Code Playgroud)
在这种情况下使用lambdas有什么用?
我对以下代码感到困惑
public static void main(String[] args) throws InterruptedException
{
Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
List<Integer> listOfIntegers =
new ArrayList<>(Arrays.asList(intArray));
List<Integer> parallelStorage = new ArrayList<>();//Collections.synchronizedList(new ArrayList<>());
listOfIntegers
.parallelStream()
// Don't do this! It uses a stateful lambda expression.
.map(e -> {
parallelStorage.add(e);
return e;
})
.forEachOrdered(e -> System.out.print(e + " "));
System.out.println();
parallelStorage
.stream()
.forEachOrdered(e -> System.out.print(e + " "));
System.out.println();
System.out.println("Sleep 5 sec");
TimeUnit.SECONDS.sleep(5);
parallelStorage
.stream()
.forEachOrdered(e -> System.out.print(e + " "));
}
Run Code Online (Sandbox Code Playgroud)
EveryTime执行它我得到了不同的结果,这让我很困惑,这里有一些结果: …
我正在开发一个我正在使用Java8 Time的应用程序.我正面临一个问题.
假设时间A是08:00,时间B是17:00,所以这两次之间的差异将是9h,在我的情况下是正确的,但如果时间A是18:00而时间B是02:00它应该是8h,但在我的情况下我的程序返回-16.请有人指导我如何解决这个问题.
我的代码:
@Test
public void testTime()
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");
String s = "18:00";
String e = "02:00";
// Parse datetime string to java.time.LocalDateTime instance
LocalTime startTime = LocalTime.parse(s, format);
LocalTime endTime = LocalTime.parse(e, format);
String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
+ ChronoUnit.MINUTES.between(startTime, endTime)%60;
System.out.println(calculatedTime);
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用IntStream来增加流外部的int值.此方法的目的是查找相同位置上是否存在不相等的字符.n和单词字符串的长度相同.
当我尝试在forEach范围内递增计数器时,它向我显示它应该是最终的或有效的最终.任何人都可以建议一个更好的方法来做这个或增加这个计数器的方法?
public boolean check(String n,String word){
int counter=0;
IntStream.range(0, n.length())
.forEach(z->{
if(n.charAt(z)!=word.charAt(z)){
counter++;
}
});
if(counter>1)
return false;
else
return true;
}
Run Code Online (Sandbox Code Playgroud) 我不打算在下面的情况下进行多次空检查,而是计划添加一些可读的代码.可以借助java 8流/地图.有人可以帮我这个
private String getRailsServiceClass(IRailsComponent railsComponent) {
String serviceClass = "";
if (railsComponent != null && railsComponent.getRailOffer() != null && railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct() != null && railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList() != null &&
railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList() != null && railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList().get(0).getPassengerSegmentFareList() != null &&
railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList().get(0).getPassengerSegmentFareList().get(0).getCarrierServiceClassDisplayName() != null) {
return railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList().get(0).getPassengerSegmentFareList().get(0).getCarrierServiceClassDisplayName();
}
return serviceClass;
}
Run Code Online (Sandbox Code Playgroud) 我试图读取目录的所有子目录中的所有文件.我写了逻辑,但我做了一些稍微错误的事情,因为它在每个文件中读取两次.
为了测试我的实现,我创建了一个包含三个子目录的目录,每个子目录中包含10个文档.这应该是30份文件.
这是我正确阅读文档的测试代码:
String basePath = "src/test/resources/20NG";
Driver driver = new Driver();
List<Document> documents = driver.readInCorpus(basePath);
assertEquals(3 * 10, documents.size());
Run Code Online (Sandbox Code Playgroud)
哪里Driver#readInCorpus有以下代码:
public List<Document> readInCorpus(String directory)
{
try (Stream<Path> paths = Files.walk(Paths.get(directory)))
{
return paths
.filter(Files::isDirectory)
.map(this::readAllDocumentsInDirectory)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.emptyList();
}
private List<Document> readAllDocumentsInDirectory(Path path)
{
try (Stream<Path> paths = Files.walk(path))
{
return paths
.filter(Files::isRegularFile)
.map(this::readInDocumentFromFile)
.collect(Collectors.toList());
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.emptyList();
}
private Document readInDocumentFromFile(Path path) …Run Code Online (Sandbox Code Playgroud) 在解析XML文件时,我的文档构建器正在寻找DTD,有时它会引发错误(服务器崩溃)。因此,当我用Google搜索时,从这里得到了以下解决方案,在解析XML时忽略了DTD(我使用的解决方案是VOTE --- 90)。我的IDE中的字母显示以下错误。
The method setFeature(String, boolean) is undefined for the type DocumentBuilderFactory
然后我认为这是我的Maven版本的问题,然后找到了以下链接。
它说它是内置在JDK中的,所以IDE本身会建议我导入。
我的JDK版本是
Java版本“ 1.8.0_121” Java™SE运行时环境(内部版本1.8.0_121-b13)Java HotSpot(TM)64位服务器VM(内部版本25.121-b13,混合模式)