Is it possible to use the Java 8 Stream API on Android API < 24?

后端 未结 6 2020
南笙
南笙 2020-11-28 06:15

I\'ve read this post here. But still I cannot run code containing Java 8 Stream API features like the following on minSdkVersion < 24.

List new         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 06:47

    Create a İnterface.

    public interface Pre {
                R get(T item);
            }
    

    Create a Filter Method.

    public static   List Filter(List list, Pre pre) {
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            {
                return list.stream().filter(p -> pre.get(p)).collect(Collectors.toList());
            }
            else
            {
                List col = new ArrayList();
                for (int i = 0 ; i < list.size() ; i++)
                    if (pre.get(list.get(i)))
                        col.add(list.get(i));
                return col;
            }
        }
    

    Using Code

        public static class model {
                public String Name;
            }
    List models = new ArrayList<>();
                ...
                List filtermodels = Filter(models,p-> p.Name.equals("filter"));
    

提交回复
热议问题