簡體   English   中英

僅使用兩個鍵和奇數或偶數列表索引作為值將 List 轉換為 Map - Java 8 Stream

[英]Transform List into Map using only two keys and odd or even list indexes as values - Java 8 Stream

我想將列表轉換為地圖,僅使用兩個字符串值作為鍵值。 然后作為值只是包含來自輸​​入列表的奇數或偶數索引位置的元素的字符串列表。 這是舊時尚代碼:

Map<String, List<String>> map = new HashMap<>();

List<String> list = Arrays.asList("one", "two", "three", "four");

map.put("evenIndex", new ArrayList<>());
map.put("oddIndex", new ArrayList<>());
for (int i = 0; i < list.size(); i++) {
    if(i % 2 == 0)
        map.get("evenIndex").add(list.get(i));
    else 
        map.get("oddIndex").add(list.get(i));
}

如何使用流將此代碼轉換為 Java 8 以獲得此結果?

{evenIndex=[one, three], oddIndex=[two, four]}

我目前的混亂嘗試需要修改列表的元素,但絕對是更好的選擇。

List<String> listModified = Arrays.asList("++one", "two", "++three", "four");

map = listModified.stream()
           .collect(Collectors.groupingBy(
                               str -> str.startsWith("++") ? "evenIndex" : "oddIndex"));

或者也許有人幫我解決這個不正確的解決方案?

IntStream.range(0, list.size())
         .boxed()
         .collect(Collectors.groupingBy( i -> i % 2 == 0 ? "even" : "odd",
                  Collectors.toMap( (i -> i ) , i -> list.get(i) ) )));

返回這個:

{even={0=one, 2=three}, odd={1=two, 3=four}}

您在對索引進行流式傳輸時走在正確的軌道上:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

IntStream.range(0,list.size())
        .boxed()
        .collect(groupingBy(
                i -> i % 2 == 0 ? "even" : "odd", 
                mapping(list::get, toList())
        ));

如果你同意你的地圖被一個boolean索引,你可以使用partitioningBy

IntStream.range(0, list.size())
        .boxed()
        .collect(partitioningBy(
                i -> i % 2 == 0, 
                mapping(list::get, toList())
        ));

您可以使用Collectors.toMap實現相同的目的; 只是為了好玩:

Map<String, List<String>> map = IntStream.range(0, list.size())
            .boxed()
            .collect(Collectors.toMap(
                    x -> x % 2 == 0 ? "odd" : "even",
                    x -> {
                        List<String> inner = new ArrayList<>();
                        inner.add(list.get(x));
                        return inner;
                    },
                    (left, right) -> {
                        left.addAll(right);
                        return left;
                    },
                    HashMap::new));

    System.out.println(map);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

Map<String, Integer> map1 = list.stream().collect(Collectors.groupingBy(e -> e % 2 == 0 ? "EvenSum" : "OddSum", Collectors.summingInt(Integer::intValue)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM