小编ETO*_*ETO的帖子

编写一个程序,使用`replace`方法在一个字符串中交换字母"e"和"o"

例如,如果我有Hello World它应该成为Holle Werld.我怎么能用这个String.replace呢?我已经尝试过,"Hello World".replace("e","o")但我只能得到Hollo World,如果我再次使用它,我会得到Helle Werld.

java collections java-8 java-stream

5
推荐指数
1
解决办法
161
查看次数

在文件系统中搜索数据的性能优化

我有一个网络相关存储,其中大约有500万个txt文件与大约300万个交易相关.总数据大小约为3.5 TB.我必须在该位置搜索以查找交易相关文件是否可用,并且必须将两个单独的报告作为"可用文件"和"不可用文件"的CSV文件.我们仍然在JAVA 6.我面临的挑战因为我必须递归搜索该位置,因为巨大的尺寸,我需要大约2分钟才能在该位置进行搜索.我正在使用Java I/O API来递归搜索,如下所示.有什么方法可以改善性能吗?

File searchFile(File location, String fileName) {
     if (location.isDirectory()) {
         File[] arr = location.listFiles();
         for (File f : arr) {
             File found = searchFile(f, fileName);
             if (found != null)
                 return found;
         }
     } else {
         if (location.getName().equals(fileName)) {
             return location;
         }
     }
     return null;
}
Run Code Online (Sandbox Code Playgroud)

java optimization search file

5
推荐指数
1
解决办法
97
查看次数

java.util.IllegalFormatConversionException: f != java.lang.Integer

我正在尝试创建一个简单的java程序,该程序读取浮点数,使用欧拉数方程计算它,然后将结果从double转换为int。我可以让它编译而不会出现错误,但在输入浮点数后出现错误:

\n
nB = Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer\n    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)\n    at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)\n    at java.util.Formatter$FormatSpecifier.print(Unknown Source)\n    at java.util.Formatter.format(Unknown Source)\n    at java.io.PrintStream.format(Unknown Source)\n    at java.io.PrintStream.printf(Unknown Source)\n    at Ex4.main(Ex4.java:16)\n
Run Code Online (Sandbox Code Playgroud)\n

它只有几行代码,我刚刚创建了一个运行良好的类似程序,所以我不明白这里出了什么问题!我认为这可能与欧拉数上的行有关,因为我还没有完全理解所有数学函数,但我在以完全相同的方式使用 \xcf\x80 之前就很好了。还是因为最后的转换步骤错误?抱歉,如果这是非常明显的事情,我已经尽力调试它很多次了,但每当我更改某个部分时,我认为这可能是问题所在,我最终会遇到更多错误。这是代码:

\n
import static java.lang.Math.*;\nimport java.util.Scanner;\n\nclass Ex4\n{\n    public static void main( String [ ] args)\n    {\n        Scanner input = new Scanner(System.in);         //import scanner and ask user to input number\n        System.out.print("Please enter a floating-point number: ");\n        double nA = input.nextDouble();     \n\n        double nB = Math.pow(E, nA); …
Run Code Online (Sandbox Code Playgroud)

java format string-formatting java-8

5
推荐指数
1
解决办法
8552
查看次数

Java 8 -reduce(0, Integer::sum) 和reduce(0, (a, b) -> a+b) 之间的区别

我是新手Java 8,确实找到了一些方法additionmultiply并且subtraction。我将发布仅用于添加的问题。

我编写了下面的代码并在 Sum1 和 Sum2 中收集输出。这两种方法reduce(0, Integer::sum)给出.reduce(0, (a, b) -> a+b);了相同的结果。如果使用大整数值,最好的使用性能的方法是什么?为什么?

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);

Integer sum1 = numbers.stream().reduce(0, (a, b) -> a+b);
System.out.println("SUM ="+sum1);

Integer product = numbers.stream().reduce(0, (a, b) -> a*b);
System.out.println("PRODUCT = "+product);

int sum2 = numbers.stream().reduce(0, Integer::sum);
System.out.println("SUM 2= "+sum2);

Optional<Integer> sum3 = numbers.stream().reduce((a, b) -> (a + b));
System.out.println("SUM3="+sum3);

// Updated as per  @Hadi J comment …
Run Code Online (Sandbox Code Playgroud)

java collections reduce java-8 java-stream

4
推荐指数
1
解决办法
3600
查看次数

Lambda表达式和Optional如何返回String值

我想获得一个Optional值,我有这样的东西:

Optional<String> value =

Optional.ofNullable(MyObject.getPeople())
    .ifPresent(people -> people                                                                    
        .stream()                                                                    
        .filter(person -> person.getName().equals("test1"))
        .findFirst()
        .map(person -> person.getId()));
Run Code Online (Sandbox Code Playgroud)

person.getId()应该返回一个字符串,我试过这个但它不起作用,得到不兼容的类型:void无法转换为java.util.Optional

Optional<String> value =

Optional.ofNullable(MyObject.getPeople())
    .ifPresent(people -> people                                                                    
        .stream()                                                                    
        .filter(person -> person.getName().equals("test1"))
        .findFirst()
        .map(person -> person.getId()))
        .orElse(null);
Run Code Online (Sandbox Code Playgroud)

任何的想法?谢谢

java collections lambda java-8 java-stream

4
推荐指数
1
解决办法
993
查看次数

Java 8 Streams减少了删除重复项,保留了最新的条目

我有一个Java bean,就像

class EmployeeContract {
    Long id;
    Date date;
    getter/setter
}
Run Code Online (Sandbox Code Playgroud)

如果有一个很长的列表,我们在id中有重复但有不同的日期,例如:

1, 2015/07/07
1, 2018/07/08
2, 2015/07/08
2, 2018/07/09
Run Code Online (Sandbox Code Playgroud)

如何减少此类列表仅保留最近日期的条目,例如:

1, 2018/07/08
2, 2018/07/09
Run Code Online (Sandbox Code Playgroud)

?最好使用Java 8 ...

我从一开始就开始:

contract.stream()
         .collect(Collectors.groupingBy(EmployeeContract::getId, Collectors.mapping(EmployeeContract::getId, Collectors.toList())))
                    .entrySet().stream().findFirst();
Run Code Online (Sandbox Code Playgroud)

这给了我各个组内的映射,但是我被困在如何将其收集到结果列表中 - 我的流不是太强我害怕...

java collections reduction java-8 java-stream

4
推荐指数
1
解决办法
693
查看次数

使用java8流从内部列表中检索数据

我有员工名单,每个员工都有其中的部门清单.我想让一个员工下的列表部门.这是我的代码,

List<Employee> employeeList = new ArrayList<Employee>();
List<Department> departments = employeeList.stream().filter(x-> x.getEmployeeName().equals("XXX")).filter(y -> y.getDepartmets()).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

java collections java-8 java-stream

4
推荐指数
1
解决办法
92
查看次数

没有分隔符的本地日期解析不起作用

我有一个日期格式如下:

四位数的年份,然后是两位数的周数.

例如,2018年的第四周将是20 1804年.

我在使用Java 8的LocalDateDateTimeFormatterBuilder解析这些日期时遇到了麻烦.

以下是我尝试解析日期的方法:

LocalDate.parse(
    "201804",
    new DateTimeFormatterBuilder().appendPattern("YYYYww").parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);
Run Code Online (Sandbox Code Playgroud)

执行会抛出以下异常:

java.time.format.DateTimeParseException:无法在索引0处解析文本"201804"

奇怪的是,当我在日期部分之间添加一个分隔符时,不再抛出异常:

LocalDate.parse(
    "2018 04",
    new DateTimeFormatterBuilder().appendPattern("YYYY ww").parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);
Run Code Online (Sandbox Code Playgroud)

结果是 :

2018年1月22日

格式化板是否缺少一些东西?

java datetime-format java-8 java-date

4
推荐指数
1
解决办法
148
查看次数

Stream reduce vs Stream.parallel.reduce()

我试图理解为什么这个例子的结果总是如此,这是我的例子:

 String s1 = Arrays.asList("A", "E", "I", "O", "U").stream()
                .reduce("", String::concat);
 String s2 = Arrays.asList("A", "E", "I", "O", "U").parallelStream()
                .reduce("", String::concat);

System.out.println(s1.equals(s2));
Run Code Online (Sandbox Code Playgroud)

这总是打印true,我所知道的是使用 parallelStream 我们无法预测结果有人可以解释为什么吗?

java collections reduce java-8 java-stream

4
推荐指数
1
解决办法
372
查看次数

如何将其转换为流表达式?(使用AtomicReference)

我需要更改以下代码:

protected void checkNoDuplicateLabels( List<CompileResult> compileResult ) {
    Set<Label> infos = new HashSet<>();
    for ( AbstractTypeInfo info : infoRepo.getList() ) {
        if ( info instanceof Label ) {
            Label label = (Label) info;
            if ( infos.contains( label ) ) {
                compileResult.add( new CompileResult( Severity.FATAL, MessageFormat.format( "Duplicate label found! \n Type: '{0}' \n Language: '{1}'", label.getType(), label.getLanguage() ) ) );
            }
            infos.add( label );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

进入一条小溪.我知道使用集合与流的一种方法是通过实现AtomicReferences,它将方法的第一行替换为:

AtomicReference<Set<Label>> infos = new AtomicReference<>( new HashSet<Label>() );
Run Code Online (Sandbox Code Playgroud)

如何使用流实现循环正在执行的相同功能?

java collections java-8 java-stream

3
推荐指数
1
解决办法
59
查看次数