我喜欢将以下代码转换为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;
}
答案 0 :(得分:11)
这是groupingBy
收藏家的工作:
import static java.util.stream.Collectors.groupingBy;
Map<String, List<Data>> heMap = obj.stream().collect(groupingBy(d -> getKey(d)));
请注意,这将使用 Map
和List
的某些未指定的实现。目前,它恰好是HashMap
和ArrayList
,但未来可能会发生变化。
答案 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);
}
}