使用Java 8中的Collectors.toMap映射LIst

时间:2016-04-22 02:16:59

标签: collections lambda java-8 java-stream collectors

我喜欢将以下代码转换为java流,

HashMap<String, List<Data>> heMap = new HashMap<String, List<Data>>();
for (Data heData : obj) {
    String id = heData.getData().getId() + heData.getPlanData().getCode()
            + heData.getPlanData().getId();
    if (!heMap.containsKey(id)) {
        CitizenHElist = new ArrayList<Data>();

        CitizenHElist.add(heData);
        heMap.put(id, CitizenHElist);

    } else {
        heMap.get(id).add(heData);
    }
}

我使用流尝试了以下代码,但我没有成功。

heMap=obj.stream().collect(Collectors.toMap(t->getKey(t), obj.stream().collect(Collectors.toList())));

private String getKey(Data heData){
    String id = heData.getData().getId() + heData.getPlanData().getCode()
                    + heData.getPlanData().getId();
    return id;
}

3 个答案:

答案 0 :(得分:11)

这是groupingBy收藏家的工作:

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

Map<String, List<Data>> heMap = obj.stream().collect(groupingBy(d -> getKey(d)));

请注意,这将使用 MapList的某些未指定的实现。目前,它恰好是HashMapArrayList,但未来可能会发生变化。

答案 1 :(得分:0)

不确定您的数据结构,但您想要执行类似下面的操作。

      //set Adapter to view pager  
 viewPager.setAdapter(viewAdapter);  

 //set tablayout with viewpager  
 tabLayout.setupWithViewPager(viewPager);  

 // adding functionality to tab and viewpager to manage each other when a page is changed or when a tab is selected  
 pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));  

       //Setting tabs from adpater  
 tabLayout.setTabsFromPagerAdapter(viewAdapter);

答案 2 :(得分:0)

基于字段分组-

import java.util.*;
import java.util.stream.*;
public class Main
{
  public static void main (String[]args)
  {
    System.out.println ("Hello World");

    List < Data > dataList = getDataList();

    System.out.println (dataList);

    Map < String, List < Data >> dataMap =
      dataList.stream ().collect (Collectors.groupingBy (d->d.code));

    System.out.println (dataMap);
  }

 static List < Data > getDataList(){
    List < Data > dataList = new ArrayList <> ();
    dataList.add (new Data (1, "Prince", "102"));
    dataList.add (new Data (2, "Rahul", "102"));
    dataList.add (new Data (3, "Sunny", "103"));
    dataList.add (new Data (4, "Mitul", "104"));
    dataList.add (new Data (5, "Amit", "105"));
    dataList.add (new Data (6, "Ashish", "105"));
    return dataList;
  }
}

class Data
{
   int id;
   String name;
   String code;
  public Data (int id, String name, String code)
  {
    this.id = id;
    this.name = name;
    this.code = code;
  }
  public String toString ()
  {
    return String.format ("id:%s,name:%s,code:%s", id, name, code);
  }
}