List<Map<String, Object>>中有key为qty,如何分别统计qty= 1和qty=-1元素数量
时间: 2023-12-14 22:36:12 浏览: 160
可以使用Java 8中的流(Stream)和过滤(Filter)操作来完成这个任务。具体的代码如下:
```java
List<Map<String, Object>> list = ... // 假设已经有一个List<Map<String, Object>>对象
long qty1Count = list.stream()
.filter(map -> map.containsKey("qty") && map.get("qty").equals(1))
.count();
long qtyMinus1Count = list.stream()
.filter(map -> map.containsKey("qty") && map.get("qty").equals(-1))
.count();
```
上述代码中,首先使用`stream()`方法将`List`转换为`Stream`对象,然后使用`filter()`方法对每个`Map`进行过滤,只保留`qty`等于1或者等于-1的元素。最后使用`count()`方法统计符合条件的元素数量。其中,`qty1Count`表示`qty`等于1的元素数量,`qtyMinus1Count`表示`qty`等于-1的元素数量。
相关问题
List<Map<String, Object>>中如何统计key=qty的元素数量
可以使用Java 8的stream和filter方法来统计List中key为"qty"的元素数量。具体代码如下:
```
long count = list.stream().filter(map -> map.containsKey("qty")).count();
```
这里的`list`是指要统计的`List<Map<String, Object>>`,`count()`方法返回统计结果的数量,即key为"qty"的元素数量。
Android页面顶部有tab标签,每个tab标签有对应的列表数据,但是加载数据后,列表数据不能上下滚动,activity代码: public class ActivityTaskCenter extends Activity { private ImageView imgBack; private Button btnRefresh; private TextView tvTitle; private LinearLayout tabLayout; private HorizontalScrollView tabScrollView; private SwipeMenuListView taskListView; private List<Map<String,Object>> dataList = new ArrayList<>(); private final static int SCANNIN_GREQUEST_ORDER = 1000; private String userid = ""; private String whseid = ""; private int currentTab = 0; private TaskCenterAdapter taskCenterAdapter = null; public ActivityTaskCenter.TaskCenterAdapter getMyActivityTaskCenter() { return taskCenterAdapter; } public List<Map<String, Object>> getTaskCenterList() { return dataList; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task); imgBack = this.findViewById(R.id.id_title_btnBack); btnRefresh = this.findViewById(R.id.id_title_btnRefrush); tvTitle = this.findViewById(R.id.id_title_tip); tabScrollView = findViewById(R.id.tabScrollView); tabLayout = findViewById(R.id.tabLayout); taskListView = findViewById(R.id.id_taskcenter_listview); initView(); // 初始化标签栏 initTabs(); initEvent(); // 延迟加载确保布局已完成 taskListView.post(() -> loadData(0)); taskListView.setScrollContainer(true); taskListView.requestLayout(); } private void initView(){ try{ tvTitle.setText("任务中心"); btnRefresh.setVisibility(View.GONE); //初始化等待界面 Config.m_pDoalog = new ProgressDialog(ActivityTaskCenter.this); Config.m_pDoalog.setProgressStyle(ProgressDialog.STYLE_SPINNER); userid = SharedPreferencesUtil.GetData(getApplication(), "username", "").toString(); whseid = SharedPreferencesUtil.GetData(getApplication(), "whseid", "").toString(); taskCenterAdapter = new TaskCenterAdapter(); taskListView.setAdapter(taskCenterAdapter); taskListView.setNestedScrollingEnabled(true); }catch (Exception e){ e.printStackTrace(); } } private void initTabs() { String[] tabTitles = {"未领取", "已领取", "已完成"}; int activeColor = getResources().getColor(R.color.color_yelloworange); int inactiveColor = getResources().getColor(android.R.color.black); for (int i = 0; i < tabTitles.length; i++) { TextView tab = new TextView(this); tab.setTag(i); tab.setText(tabTitles[i]); tab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); tab.setGravity(Gravity.CENTER); tab.setPadding(32, 16, 32, 16); // 设置初始状态 if (i == currentTab) { tab.setBackgroundColor(getResources().getColor(android.R.color.white)); tab.setTextColor(activeColor); tab.getPaint().setFakeBoldText(true); } else { tab.setBackgroundColor(getResources().getColor(R.color.color_yelloworange)); tab.setTextColor(inactiveColor); } LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); tab.setLayoutParams(params); // 设置点击监听 tab.setOnClickListener(v -> { int tabIndex = (int) v.getTag(); switchTab(tabIndex); loadData(tabIndex); currentTab = tabIndex; }); tabLayout.addView(tab); } } private void switchTab(int tabIndex) { // 更新UI样式 for (int i = 0; i < tabLayout.getChildCount(); i++) { TextView tab = (TextView) tabLayout.getChildAt(i); if (i == tabIndex) { tab.setBackgroundColor(getResources().getColor(android.R.color.white)); tab.setTextColor(getResources().getColor(R.color.color_yelloworange)); tab.getPaint().setFakeBoldText(true); } else { tab.setBackgroundColor(getResources().getColor(R.color.color_yelloworange)); tab.setTextColor(getResources().getColor(android.R.color.white)); tab.getPaint().setFakeBoldText(false); } } // 确保选中的标签可见 tabScrollView.smoothScrollTo(tabLayout.getChildAt(tabIndex).getLeft(), 0); currentTab = tabIndex; } private int dp2px(int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics()); } private void initEvent(){ try { imgBack.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ActivityTaskCenter.this.finish(); } }); } catch (Exception e) { throw new RuntimeException(e); } } private final Handler TaskCenterHandle = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { try{ switch (msg.what){ case SCANNIN_GREQUEST_ORDER: Document doc = new Document(new Element("NewDataSet")); Element rootEle = doc.getRootElement(); Element licUserEle = new Element("RecCheck"); licUserEle.addContent(new Element("userid").addContent(userid)); licUserEle.addContent(new Element("whseid").addContent(whseid)); rootEle.addContent(licUserEle); PostWebservices.webSend(ActivityTaskCenter.this,new HandlerMsg(ActivityTaskCenter.this),47, DomUtil.doc2xmlStr(doc)); break; } }catch (Exception e){ e.printStackTrace(); Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } return true; } }); private void loadData(int tabIndex) { dataList.clear(); switch (tabIndex) { case 0: // 未领取 getLoadData(47); break; case 1: // 已领取 getLoadData(48); break; case 2: // 已完成 getLoadData(49); break; } } public void refresh(){ getLoadData(currentTab); } public void playErrorSound(Context context) { MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.beep); if (mediaPlayer != null) { mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); // 播放完成后释放资源 } }); mediaPlayer.start(); } } public class TaskCenterAdapter extends BaseAdapter { @Override public int getCount() { return dataList == null ? 0 : dataList.size(); } @Override public Object getItem(int i) { return dataList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ convertView = View.inflate(getApplicationContext(),R.layout.item_listview4taskcenter,null); new ActivityTaskCenter.TaskCenterAdapter.ViewHolderForOutBound(convertView); } ViewHolderForOutBound holder = (ViewHolderForOutBound) convertView.getTag(); final Map<String, Object> item = (Map<String, Object>) getItem(position); holder.task_orderno.setText(item.get("receiptkey").toString()); holder.task_adddate.setText(item.get("adddate").toString()); holder.task_tasktype.setText(item.get("task_type").toString()); holder.task_status.setText(item.get("status").toString()); holder.task_customer.setText(item.get("company").toString()); holder.task_pre_qty.setText(item.get("pre_qty").toString()); holder.task_goods_count.setText(item.get("goods_count").toString()); holder.btnReceive.setTag(position); convertView.setFocusable(true); convertView.setClickable(true); return convertView; } class ViewHolderForOutBound{ private TextView task_orderno; private TextView task_adddate; private TextView task_tasktype; private TextView task_status; private TextView task_customer; private TextView task_pre_qty; private TextView task_goods_count; private Button btnReceive; public ViewHolderForOutBound(View view){ task_orderno = (TextView) view.findViewById(R.id.id_taskcenter_receiptkey); task_adddate = (TextView) view.findViewById(R.id.id_taskcenter_adddate); task_tasktype = (TextView) view.findViewById(R.id.id_taskcenter_tasktype); task_status = (TextView) view.findViewById(R.id.id_taskcenter_status); task_customer = (TextView) view.findViewById(R.id.id_taskcenter_customer); task_pre_qty = (TextView) view.findViewById(R.id.id_taskcenter_pre_qty); task_goods_count = (TextView) view.findViewById(R.id.id_taskcenter_goods_count); btnReceive = (Button) view.findViewById(R.id.btn_task_claim); btnReceive.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { int position = (int) view.getTag(); // 从 tag 中获取 position Map<String, Object> item = (Map<String, Object>) dataList.get(position); String receiptKey = item.get("receiptkey").toString(); String task_type = item.get("task_type").toString(); int msgwhat = 50; if(task_type.equals("验货任务")){ msgwhat = 50; } else if (task_type.equals("拣货任务")) { msgwhat = 51; }else if (task_type.equals("发货任务")) { msgwhat = 52; } Config.m_pDoalog.setMessage("请稍等..."); Config.m_pDoalog.setIndeterminate(false); Config.m_pDoalog.setCancelable(false); Config.m_pDoalog.show(); Document doc = new Document(new Element("NewDataSet")); Element rootEle = doc.getRootElement(); Element licUserEle = new Element("RecCheck"); licUserEle.addContent(new Element("userid").addContent(userid)); licUserEle.addContent(new Element("whseid").addContent(whseid)); licUserEle.addContent(new Element("orderkey").addContent(receiptKey)); rootEle.addContent(licUserEle); PostWebservices.webSend(ActivityTaskCenter.this,new HandlerMsg(ActivityTaskCenter.this),msgwhat, DomUtil.doc2xmlStr(doc)); } }); view.setTag(this); } } } public void showData(List<Map<String, Object>> dataList){ this.dataList = dataList; taskCenterAdapter.notifyDataSetChanged(); } public void getLoadData(int msgwhat){ Config.m_pDoalog.setMessage("请稍等..."); Config.m_pDoalog.setIndeterminate(false); Config.m_pDoalog.setCancelable(false); Config.m_pDoalog.show(); Document doc = new Document(new Element("NewDataSet")); Element rootEle = doc.getRootElement(); Element licUserEle = new Element("RecCheck"); licUserEle.addContent(new Element("userid").addContent(userid)); licUserEle.addContent(new Element("whseid").addContent(whseid)); rootEle.addContent(licUserEle); PostWebservices.webSend(ActivityTaskCenter.this,new HandlerMsg(ActivityTaskCenter.this),msgwhat, DomUtil.doc2xmlStr(doc)); } public void setCloseProDialog(){ Config.m_pDoalog.hide(); } } activity_task代码: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#F5F5F5"> <!-- 固定顶部的标签栏 --> <HorizontalScrollView android:id="@+id/tabScrollView" android:layout_width="match_parent" android:layout_height="40dp" android:fillViewport="true" android:scrollbars="none" android:background="@color/color_yelloworange"> <LinearLayout android:id="@+id/tabLayout" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" /> </HorizontalScrollView> <com.likelic.wmsassistantbyadp.baoyz.swipemenulistview.SwipeMenuListView.SwipeMenuListView android:id="@+id/id_taskcenter_listview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:divider="#EEEEEE" android:dividerHeight="2px" android:scrollbars="vertical" android:nestedScrollingEnabled="true"/> </LinearLayout>
<think>我们正在解决SwipeMenuListView在数据加载后无法上下滚动的问题。根据提供的引用和常见问题,可能的原因包括:
1. 布局高度问题:ListView的父容器可能没有正确设置高度,或ListView自身高度设置不当。
2. 触摸事件冲突:SwipeMenuListView可能与其他手势操作冲突。
3. 适配器问题:数据加载后未正确通知适配器更新。
4. 嵌套滚动冲突:如果ListView被嵌套在可滚动的父容器中(如ScrollView),则会导致滚动冲突。
解决方案:
1. **检查布局高度**:确保ListView的高度设置为`match_parent`或固定高度,而不是`wrap_content`,特别是在嵌套在ScrollView中时。但注意,通常不应该将ListView嵌套在ScrollView中,因为这样会导致滚动冲突。如果必须嵌套,可以自定义ListView,重写其`onMeasure`方法,使其能够展开所有项,但这会失去ListView的复用机制,性能差。因此,建议避免嵌套。
2. **避免嵌套滚动容器**:如果SwipeMenuListView被放在ScrollView中,移除ScrollView,改用其他布局方式。如果需要多个可滚动区域,考虑使用NestedScrollView(在支持库中)并只包含一个直接子布局,然后在其中放置多个可滚动视图(但ListView本身可滚动,所以通常不需要再嵌套)。
3. **检查触摸事件冲突**:SwipeMenuListView可能因为处理了水平滑动菜单而影响了垂直滚动。可以检查SwipeMenuListView的源码或文档,看是否有相关设置可以调整触摸灵敏度或滑动方向优先级。
4. **确保适配器更新**:在数据加载完成后,确保调用了适配器的`notifyDataSetChanged()`方法,以便ListView刷新显示。
5. **自定义ListView解决嵌套问题**:如果确实需要嵌套,可以自定义ListView,重写`onMeasure`方法,使其可以展开。但这种方法只适用于数据量小的情况,因为会一次性加载所有项。
示例代码(自定义ListView解决嵌套在ScrollView中的高度问题):
```java
public class ExpandableHeightListView extends ListView {
boolean expanded = false;
public ExpandableHeightListView(Context context) {
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// HACK! 解决嵌套显示不全的问题
if (isExpanded()) {
// 根据模式计算高度
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
```
然后在布局中使用`ExpandableHeightListView`代替`ListView`,并设置`expanded`为`true`。
但是,更推荐的方法是避免嵌套,使用单个可滚动视图。
6. **检查是否有其他覆盖层**:检查是否有其他视图覆盖在ListView上,导致触摸事件被拦截。
7. **检查SwipeMenuListView的配置**:查看SwipeMenuListView的文档,看是否有启用滚动的设置。
根据引用[2],我们绑定了SwipeMenuListView,并设置了适配器。如果问题出现在数据加载后,那么可能是数据加载后没有正确刷新视图,或者数据加载过程中出现了异常导致ListView无法滚动。
**步骤总结:**
- 检查布局,确保ListView高度设置正确且没有不必要的嵌套。
- 避免嵌套在ScrollView中,如果必须嵌套,使用上述自定义ListView或改用NestedScrollView(并注意只允许一个直接子视图)。
- 在数据加载完成后,在主线程调用`adapter.notifyDataSetChanged()`。
- 检查日志,看是否有异常导致ListView渲染失败。
如果以上方法都不能解决问题,请提供更多上下文信息,例如布局文件代码和加载数据的具体代码。
相关问题:
1. 如何避免Android中嵌套滚动视图的冲突?
2. SwipeMenuListView如何自定义菜单项的样式?
3. 在ListView中加载大量数据时如何优化性能?</think>### Android SwipeMenuListView 数据加载后无法上下滚动的解决方案
#### 问题分析
当 SwipeMenuListView 数据加载后无法滚动时,通常由以下原因导致:
1. **布局嵌套问题**:ListView 被嵌套在不可滚动的容器中(如 LinearLayout),且未设置正确的高度约束[^2]
2. **高度计算错误**:ListView 的 `layout_height` 设置为 `wrap_content` 但未正确计算内容高度
3. **触摸事件冲突**:侧滑菜单的触摸事件处理干扰了滚动事件
4. **适配器未刷新**:数据更新后未调用 `notifyDataSetChanged()`
#### 解决方案
##### 1. 修复布局高度(最常见)
在 XML 布局文件中,确保 ListView 高度设置为 `match_parent` 或使用权重:
```xml
<com.fortysevendeg.swipelistview.SwipeListView
android:id="@+id/swipe_menu_listview"
android:layout_width="match_parent"
android:layout_height="match_parent" /> <!-- 关键修改 -->
```
##### 2. 避免嵌套滚动容器
不要将 SwipeListView 嵌套在 ScrollView 中:
```diff
- <ScrollView>
- <SwipeListView.../> <!-- 错误嵌套 -->
- </ScrollView>
+ <FrameLayout> <!-- 正确容器 -->
+ <SwipeListView.../>
+ </FrameLayout>
```
##### 3. 动态计算高度(特殊场景)
若必须使用 `wrap_content`,重写 ListView 的测量方法:
```java
public class DynamicHeightListView extends SwipeListView {
public DynamicHeightListView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
// 允许高度扩展到最大
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthSpec, expandSpec);
}
}
```
##### 4. 检查适配器刷新
数据更新后必须通知适配器:
```java
swipeListView.setAdapter(adapter);
adapter.addAll(newData); // 添加数据
adapter.notifyDataSetChanged(); // 强制刷新视图
```
##### 5. 解决触摸冲突
在自定义适配器中处理事件分发:
```java
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setOnTouchListener((v, event) -> {
// 当检测到垂直滚动时禁用侧滑
if (Math.abs(event.getY() - startY) > touchSlop) {
swipeListView.setSwipeEnabled(false);
}
return false;
});
return view;
}
```
#### 验证步骤
1. 检查布局文件是否符合高度约束要求
2. 确保数据加载后调用了 `notifyDataSetChanged()`
3. 在 `onCreate()` 中添加测试数据验证基础功能:
```java
swipeListView.postDelayed(() -> {
List<String> testData = Arrays.asList("测试项1", "测试项2", "测试项3");
adapter.addAll(testData);
adapter.notifyDataSetChanged();
}, 1000);
```
> **提示**:如果使用第三方库(如 Android-PullToRefresh[^1]),需确保其与 SwipeListView 的兼容性,避免手势冲突。
#### 相关问题
1. 如何优化 SwipeMenuListView 在数据量大的情况下的性能?
2. SwipeMenuListView 如何实现自定义菜单项动画效果?
3. 如何处理 SwipeMenuListView 与下拉刷新控件的冲突?
4. 在 SwipeMenuListView 中如何实现分组粘性头部效果?[^3]
阅读全文
相关推荐







