标签: java-8

如何使用Java 8从字符串中提取子字符串?

我有一个9位数字的字符串,其中包括以下详细信息:前3位数字代表城市代码,中间3位是银行代码,最后3位是分支代码。

我想使用Java 8或函数式编程从整个字符串中提取这3个,以便随时可以更改实现。

我已经使用了旧的基本结构,使用 String.substring(start,end);


    public static void main(String[] args) {

        String city = getCityCode("302105202");

        System.out.println("City-" + city);

        String bank = getBankCode("302105202");

        System.out.println("bank-" + bank);

        String branch = getBranchCode("302105202");

        System.out.println("branch-" + branch);

    }

    public static String getCityCode(String micr) {
        return micr.substring(0, 3);
    }

    public static String getBankCode(String micr) {
        return micr.substring(3, 6);
    }

    public static String getBranchCode(String micr) {
        return micr.substring(6, 9);
    }

}

Run Code Online (Sandbox Code Playgroud)

如何在Java 8中获得这些?

提前致谢;

java functional-programming java-8

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

Java8流:流中的通用记录器方法

我想创建一种在流中打印出信息的方法。请查看我现有的记录器方法。方法参数必须是通用的,例如在我的示例字符串和整数中。在我的情况下,该方法应该返回原始对象。有人可以告诉我当前方法有什么问题吗?

在此先多谢!

看一下记录器方法

Stream<String> stream = Stream.of("A", "BC", "XYZ");

stream.map(t -> logger(t.length()))
   .map(t-> logger(t.substring(0, 2)))
   .collection(Collectors.toList());

public static <T> T logger(T t) {
    System.out.println(t);
    return t;
  }
Run Code Online (Sandbox Code Playgroud)

错误:无法推断地图的类型参数(函数)

java functional-programming java-8 java-stream

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

从列表中删除值,同时将其与列表进行比较

初学者QQ:我有一个列表和一个Map。我需要对照“列表”检查“地图”中的所有值,如果该值在地图中但不在列表中,那么我需要将其删除

    List<String> list = getRequiredList();
    Set<String> set = new HashSet<>(list)
    Map<String, String> map = getMap(); 
Run Code Online (Sandbox Code Playgroud)

需要一些有关如何从地图中删除(如果不在列表中)的信息

java java-8

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

Java泛型不适用于参数List &lt;Object&gt;

我正在玩Java中的泛型。但是我确实有问题。简而言之,这段代码应该转换一个列表中的一个对象,而不是将其放入另一个列表中。(从T到U)

我的代码看起来像这样

public class ListConvertor<T, U> {

    private final Convertor<T, ? extends U> convertor;

    public ListConvertor( Convertor<T, ? extends U> convertor ) {
        this.convertor = convertor;
    }

    public void convertList( List<T> from, List<U> to ) {
        if ( from == null )
            return;

        for ( T ch : from ) {
            to.add( convertor.convert( ch ) );
        }
    }
}

public interface Convertor<T, V> {

    V convert( T dataModelObject ) throws JEDXException;

}
Run Code Online (Sandbox Code Playgroud)

对于以下内容,它可以正常工作:

new ListConvertor<>(new IntListConvertor()).convertList(in.getIntLists(), out.getIntLists());
Run Code Online (Sandbox Code Playgroud)

当像上面那样使用此代码时,一切正常,因为intand …

java java-8

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

当ForkJoinPool结束时

我试图找出所有ForkJoinPool线程何时完成其任务。我写了这个测试应用程序(我使用System.out是因为它只是一个快速的测试应用程序,并且没有错误检查/处理):

public class TestForkJoinPoolEnd {
    private static final Queue<String> queue = new LinkedList<>();
    private static final int MAX_SIZE = 5000;
    private static final int SPEED_UP = 100;

    public static void main(String[] args) {
        ForkJoinPool customThreadPool = new ForkJoinPool(12);
        customThreadPool.submit(
                () -> makeList()
                        .parallelStream()
                        .forEach(TestForkJoinPoolEnd::process));
        enqueue("Theard pool started up");

        int counter = MAX_SIZE + 1;
        while (!customThreadPool.isTerminating()) {
            String s = dequeue();
            if (s != null) {
                System.out.println(s);
                counter--;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {

            }
        }
        System.out.println("counter …
Run Code Online (Sandbox Code Playgroud)

java parallel-processing java-8 java-stream

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

什么时候在Java中使用Identity函数?

通过一些代码,并遇到Function.identity(),我发现它类似于s-> s。我不明白为什么以及何时应该使用Function.identity()。

我试图通过一个例子来理解,但是并没有阐明我的问题:

public static void main(String[] args){
        Arrays.asList("a", "b", "c")
          .stream()
          .map(Function.identity())
          //.map(str -> str)   //it is the same as identity()       
          .forEach(System.out::println);
        return;
    }
Run Code Online (Sandbox Code Playgroud)

当打印带有和不带有映射的列表元素时,我得到相同的结果:

a
b
c
Run Code Online (Sandbox Code Playgroud)

那么,包含s-> s的目的是传递字符串并检索字符串吗?Function.identity()的目的是什么?

请给我提供一个更好的示例,也许这个示例对证明使用identity()的重要性没有意义。

谢谢

java lambda functional-programming java-8

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

Stream()。map()结果作为Collectors.toMap()的值

我想要List<InstanceWrapper>为每个元素做一些逻辑运算,从而得出一些结论String message。然后,我要进行create Map<String, String>,其中key是InstanceWrapper:ID,value是message

private String handle(InstanceWrapper instance, String status) {
    return "logic result...";
}

private Map<String, String> handleInstances(List<InstanceWrapper> instances, String status) {
    return instances.stream().map(instance -> handle(instance, status))
                    .collect(Collectors.toMap(InstanceWrapper::getID, msg -> msg));     
}
Run Code Online (Sandbox Code Playgroud)

但是它不会编译,我会明白,如何将stream().map()结果转化为collectors.toMap()价值?

The method collect(Collector<? super String,A,R>) in the type Stream<String> is not applicable for the arguments (Collector<InstanceWrapper,capture#5-of ?,Map<String,Object>>)
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

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

通用参数可重用性

我有两种不同的方法

public static void printRoutes(List<Optional<String>> routes) {
    for (int i = 0; i < routes.size(); i++) {
        if(routes.get(i).isPresent()) {
            System.out.println("Output #" + (i+1) + ": "+routes.get(i).get());
Run Code Online (Sandbox Code Playgroud)

public static void printRoutes(List<Optional<Integer>> routes) {
    for (int i = 0; i < routes.size(); i++) {
        if(routes.get(i).isPresent()) {
            System.out.println("Output #" + (i+1) + ": "+routes.get(i).get());
Run Code Online (Sandbox Code Playgroud)

如您所见,它们基本相同,但参数类型相同。由于我只是打印它们,所以使用“ .toString()”方法,我认为应该有一种对两者使用相同方法的方法。

我尝试过

public static void printRoutes(List<Optional<T super Object>> lengths) 
Run Code Online (Sandbox Code Playgroud)

public static void printRoutes(List<Optional<T extends Object>> lengths) 
Run Code Online (Sandbox Code Playgroud)

但这是行不通的,有办法吗?否则您将无法使用泛型。

java generics java-8

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

从返回Mono &lt;Void&gt;的方法进行WebFlux链接

这是我删除项目的控制器:

 public Mono<ResponseEntity> delete(
        @PathVariable(value = "id") String id) {
    return itemService.delete(id)
            .map(aVoid -> ResponseEntity.ok());
}
Run Code Online (Sandbox Code Playgroud)

itemService.delete(id) 退货 Mono<Void>

但是,当我成功删除一个项目时,它没有给我响应实体对象。它仅返回空白json。

我似乎未执行地图,因为delete方法返回 Mono<Void>

如何正确做到这一点?

java-8 project-reactor spring-webflux

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

Lambda在forEach中使用外部连接变量

我有一个创建一次的连接对象,并在forEach中使用。如果没有在forEach内部使用初始值,则无法最终使用连接对象,因为它是最终的。

final Connection connection;
        try {
            connection = db.createConnection();

            final Map<String, String> dataMap = adminClient.list().values();

            dataMap.entrySet().forEach(entry -> {

                // Need to use connection object here ...
                // Unable to use the connection if it is not final and to make it final, not initializing it to null  ...
            });

        }
        catch (final Exception e) {
            e.printStackTrace();
        }
        finally {
            // Unable to use the connection here if it is not initialized to null ...
            if (connection != null) {
                connection.close(); …
Run Code Online (Sandbox Code Playgroud)

java lambda java-8

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