标签: java-8

包含通用Map.Entry参数的方法

我有两个类非常相似的类

A类:

String getString(Set<Map.Entry<String, List<String>>> headers) {
    return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream().
            collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator()));
}
Run Code Online (Sandbox Code Playgroud)

B级

String getString(Set<Map.Entry<String, Collection<String>>> headers) {
    return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream().
            collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator()));
}
Run Code Online (Sandbox Code Playgroud)

方法参数泛型类型的唯一区别:

Set<Map.Entry<String, List<String>>> headers
Set<Map.Entry<String, Collection<String>>> headers
Run Code Online (Sandbox Code Playgroud)

我不会编码重复.并寻找方式haw我可以在一个重构这两个方法.

我正在尝试使用不同的通用通配符组合编写代码(?super或?extends).但失败了.例如:

Set<Map.Entry<String, ? extends Collection<String>>>
Run Code Online (Sandbox Code Playgroud)

你能不能支持我如何重构这个泛型的想法.谢谢

java generics generic-collections java-8

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

Java 8:如何使用ArrayList对两个嵌套的Maps进行排序和收集?

我有一个以下类型的嵌套Map LinkedHashMap<String, LinkedHashMap<String, ArrayList<Commit>>>.第一个映射的键存储一些用户名,第二个映射的键是用户的存储库名称,在ArrayList内部我有一个对象,其中包含一些属性,如哈希,消息,添加等.

在我按照第一张地图的键和第二张地图的键按字母顺序排序整个集合后,我如何在相同类型的新集合中收集(保存)我的嵌套地图(对象保持不变)?

我需要使用lambda和Stream API来做到这一点.这是我试图这样做的方式:

LinkedHashMap<String, LinkedHashMap<String, ArrayList<Commit>>> sorted = gitUsers.entrySet()
            .stream()
            .sorted((u1, u2) -> u1.getKey().compareTo(u2.getKey()))
            .map(u -> u.getValue()
                    .entrySet()
                    .stream()
                    .sorted((r1, r2) -> collator.compare(r1.getKey(), r2.getKey())))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a, b) -> a, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

我肯定做错了,因为我不断收到以下消息"无法从静态上下文中引用非静态方法"并且无法收集地图.我想我无法成功组装我的地图因为.map()我使用的功能和第二个流.

我知道你会建议我使用TreeMap或者使用.foreach()我的lambda中的方法对它进行排序并立即打印(顺便提一下我已经做过),但我需要像上面描述的那样完全按照这种方式进行排序..

出于我的编程基础课程的目的,这个问题应该以这种方式解决.希望对你有所帮助!

PS我一直在寻找解决方案很长一段时间,并在各地进行研究,包括Stack Overflow论坛,并没有找到任何对应于所要求的解决问题的方法.

java lambda hashmap java-8 java-stream

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

多个Java 8枚举使用相同的方法

我有一系列看起来像这样的枚举,除了名称和值不同:

/* Bone Diagnosis. Value is internal code stored in database. */
public enum BoneDiagnosis {
    NORMAL(121),
    ELEVATED(207),
    OSTEOPENIA(314),
    OSTEOPOROSIS(315);

    private int value;
    BoneDiagnosis(final int value) {
        this.value = value;
    }

    /** Get localized text for the enumeration. */
    public String getText() {
        return MainProgram.localize(this.getClass().getSimpleName().toUpperCase() + ".VALUE." + this.name());
    }

    /** Convert enumeration to predetermined database value. */
    public int toDB() {
        return value;
    }

    /** Convert a value read from the database back into an enumeration. */
    public static …
Run Code Online (Sandbox Code Playgroud)

java enums java-8

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

然后比较vs排序

这两个版本是否有任何区别(例如性能,订购):

版本1:

mylist.sort(myComparator.sort_item);
mylist.sort(myComparator.sort_post);
Run Code Online (Sandbox Code Playgroud)

版本2:

// java 8
mylist.sort(myComparator.sort_item
            .thenComparing(myComparator.sort_post));
Run Code Online (Sandbox Code Playgroud)

comparable java-8

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

removeIf中的lambdas

HashSet<Integer> liczby = new HashSet<Integer>();
liczby.add(1);
liczby.add(2); 
liczby.add(3);
liczby.add(4);
liczby.removeIf ((Integer any) -> { return liczby.contains(3); });

for(Iterator<Integer> it = liczby.iterator(); it.hasNext();){
    Integer l2 = it.next();
    System.out.println(l2);
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么removeIf删除不仅3,而且1和2条件只应满足3 ...

java lambda remove-if java-8

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

带有初始值的Class实例的静态arraylist

我使用静态arraylist创建了一个Coin类,它存储了所创建的类的每个实例,但我需要用初始实例启动该列表,而且我没有想到如何在不添加它的情况下执行它(因为冗余代码) ), 有什么建议?

public class Coin {
    private static ArrayList<String> coinNames = new ArrayList<>();
    private static ArrayList<String> coinAbbreviations = new ArrayList<>(Arrays.asList("CLP"));
    private static ArrayList<Coin> coins =
            new ArrayList<>(Arrays.asList(new Coin("Pesos chilenos", "CLP", 1f, "CLP")));
    private static HashMap<String,Float> exchangeRates;
    private String coinName;
    private String coinAbbreviation;
    private Float coinValue;
    private String unit;


    public Coin(String coinName, String coinAbbreviation, Float coinValue, String unit) {
        assert !coinAbbreviations.contains(coinAbbreviation) : "Coin abbreviation already used";
        assert coinAbbreviations.contains(unit) : "Coin unit non existent.";
        assert !coinNames.contains(coinName) : "Coin name already used."; …
Run Code Online (Sandbox Code Playgroud)

java arraylist static-initialization java-8

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

CompletionStage.thenCompose不按顺序执行

我正在尝试使用java 8 CompletionStages来串行执行2个异步方法,以便在第一个失败时不执行第二个异步方法.但是当我调用thenCompose时,传入的函数似乎在前一个函数完成之前开始(例如:两个函数错误地并行执行.这是代码:

  public CompletionStage<Graph> create(Payload payload) {
    CompletionStage<BlobInfo> fileFuture = createFile(payload);
    CompletionStage<Entity> metadataFuture = createMetadata(payload);
    return fileFuture
        .thenCompose(ignore -> metadataFuture)
        .thenApply(entity ->
            buildFromEntity(objectMapper, entity));
  }

  public CompletionStage<BlobInfo> createFile(Payload payload) {
    return CompletableFuture.supplyAsync(() -> {
      try {
        return
            storage.create(
                BlobInfo
                    .newBuilder(payload.bucket, payload.name)
                    .build(),
                payload.data.getBytes());
      } catch (StorageException e) {
        LOG.error("Failed to write to storage: " + e);
        throw new RequestHandlerException(StatusCode.SERVER_ERROR,
            "Failed to write to storage.");
      }
    });
  }


  public CompletionStage<Entity> createMetadata(Payload payload) {
    return CompletableFuture.supplyAsync(() -> createSync(payload));
  }

  private Entity …
Run Code Online (Sandbox Code Playgroud)

java java-8 completable-future

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

java 8 List <Pair <String,Integer >> to List <String>

有一个List>:

List<Pair<String, Integer>> list =new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

配对javafx.util.Pair有一个键和一个值.和a

Integer tmp;
Run Code Online (Sandbox Code Playgroud)

我应该如何Pair.getValue() >=tmp 通过java 8流获取所有String ?

java java-8

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

如何在Java中将BigDecimal转换为浮点数为2的小数

如何将BigDecimal转换为float,在Java中为2个小数?

BigDecimal x=new BigDecimal(any exponential term);
Run Code Online (Sandbox Code Playgroud)

现在,我想转换为仅具有2个小数点的浮点数,例如-0.45。

java bigdecimal java-8

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

Java 8可选,用于在分层对象中执行空检查

对对象使用“空检查”选项克隆不同类型的对象。

class A{ C cObj, List<B> bList;}

class B{ C cObj; List<C> cList;}

class C { String label; String value;}

class D{ String name; String age; String addressCode;}
Run Code Online (Sandbox Code Playgroud)

映射A-> D

d.setAddessCode(A.getBlist().get(0).getcList().get(0).getValue());
Run Code Online (Sandbox Code Playgroud)

如何使用Java 8可选检查null

A.getBlist().get(0).getcList().get(0).getValue()
Run Code Online (Sandbox Code Playgroud)

我试过了

d.setAddessCode(Optional.ofNullable(A).map(A::getBList).map(Stream::of).orElseGet(Stream::empty).findFirst().map(B::getCList).map(Stream::of).orElseGet(Stream::empty).findFirst().map(C::getValue).orElse(null)));
Run Code Online (Sandbox Code Playgroud)

我如何才能一起检查列表和值中的null。

java object optional java-8 java-stream

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