使用java&读取行maped过滤数据 [英] read line using java & maped filterd data

查看:101
本文介绍了使用java&读取行maped过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Reader {
        public static void main(String[] args) throws IOException, ParseException {
            BufferedReader reader;
            String animalName="cat";
            String animal = null;
            try {
                reader = new BufferedReader(new InputStreamReader(
                        new FileInputStream("C:/dila.txt")));
                Map<String, Integer> result = new LinkedHashMap<String, Integer>();
                Map<String, Integer> result2 = new LinkedHashMap<String, Integer>();

                while (reader.ready()) {
                    String line = reader.readLine();
/split a line with spaces/
                    String[] values = line.split(",");
                    String key = null;                 
                    if(values[1].compareTo(animalName)==0){
                    key = values[0];
                    animal=""+values[1].compareTo(animalName);
                    int sum = 0;
                    int count = 0;
/get a last counter and sum/
                    if (result.containsKey(key)) {
                        sum = result.get(key);
                        count = result2.get(key);
                    } else{
                    }
 /increment sum a count and save in the map with key/
                    result.put(key, sum + Integer.parseInt(values[2]));
                    result2.put(key, count + 1);
                }
                }

 /interate and print new output/
                for (String key : result.keySet()) {
                    Integer sum = result.get(key);
                    Integer count = result2.get(key);
                    System.out.println(key +"   "+animalName+ " " + sum + "\t" + count);
                }
                reader.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }




  • 我有以下文字文件

    11/2/2010,cat,6

    2010年2月2日,猫,3

    11/2/2010,狗,4

    2010年2月2日,猫,11

    11/3/2010,cat,1

    11/3/2010,dog,3

    11/3/2010,cat,8

    11/3/2010,cat,80




  • 以上代码目前正在打印此摘要数据

    11/2/2010   猫&NBSP;&NBSP;&NBSP; 20&NBSP;&NBSP;&NBSP; 3

    11/3/2010   猫&NBSP;&NBSP;&NBSP; 104&NBSP;&NBSP;&NBSP; 4

    11/4/2010   猫&NBSP;&NBSP;&NBSP; 26&NBSP;&NBSP;&NBSP; 2




  • 我需要帮助才能打印如下所示的摘要

    11/01 / 2010

    2010年2月2日   猫&NBSP;&NBSP;&NBSP; 20&NBSP;&NBSP;&NBSP; 3

    11/03/2010   猫&NBSP;&NBSP;&NBSP; 104&NBSP;&NBSP;&NBSP; 4

    11/04 / 2010   猫&NBSP;&NBSP;&NBSP; 26&NBSP;&NBSP;&NBSP; 2

    11/05/2010

    11/06/2010

    11/07/2010

    11 / 08/2010

    11/09/2010

    11/10/2010

    11/11/2010

    11/12/2010

    11/13/2010

    11/14/2010

    11/15/2010

    11/16/2010

    11/17/2010

    11/18/2010

    11/19/2010

    11/20/2010

    11/21/2010

    11/22/2010

    11/23/2010

    11/24/2010

    11/25/2010

    11/26/2010

    11/27/2010

    11/28/2010

    11/29/2010

    11/30/2010

  • 我从,中分离出大量数据。 。所以我想读线和拆分。 &安培;我做到了。但我的要求是上面显示的结果。

    i hav bulk of data seperated from "," . so iwant to read line and split. & i hav done it. but my requrment is above shown result.

    推荐答案

    以下是执行此操作的代码。我正在寻求google-guava库的帮助,因为它可以帮助我编写更少的代码;-)。如果你只想在普通的java中然后你也可以修改代码,如果逻辑需要一些调整然后看看processLine(...)方法,那就是改变将去的地方

    Below is the code to do it. I am taking help of google-guava libraries as it helps me write less code ;-). If you just want in plain java then you can modify the code also if the logic needs some tweaking then look at processLine(...) method, that is where the change will go

    好的,我看到的唯一缺失的代码是按排序顺序打印不属于输入文件的日期的空数据。这很简单,留给你。以下是提示:增加日期为1&循环直到月末

    Ok the only missing code I see is printing empty data for the dates that are not part of the input file in a sorted order. That is simple and leave it to you. Here is the hint: Increment date by 1 & loop until end of the month

    我已运行您的示例文件并打印以下摘要

    I have run your sample file and it prints the below summary

    11/3/2010   cat 89  3
    11/3/2010   dog 3   1
    11/2/2010   dog 4   1
    11/2/2010   cat 20  3
    
    
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.Map;
    
    import com.google.common.base.CharMatcher;
    import com.google.common.base.Charsets;
    import com.google.common.base.Joiner;
    import com.google.common.base.Splitter;
    import com.google.common.collect.Maps;
    import com.google.common.io.Files;
    import com.google.common.io.LineProcessor;
    
    public class AnimalSummaryBuilder
    {
        private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));
    
        private static final Joiner JOINER = Joiner.on("\t");
    
        @SuppressWarnings("unchecked")
        public static void main(final String[] args) throws Exception
        {
            @SuppressWarnings("rawtypes")
            Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
    
                private final Map<Animal, Summary> result = Maps.newHashMap();
    
                public Object getResult()
                {
                    return result;
                }
    
                public boolean processLine(final String line) throws IOException
                {
                    Iterator<String> columns = SPLITTER.split(line).iterator();
    
                    String date = columns.next();
                    String name = columns.next();
                    int value = Integer.valueOf(columns.next()).intValue();
    
                    Animal currentRow = new Animal(date, name);
    
                    if (result.containsKey(currentRow))
                    {
                        Summary summary = result.get(currentRow);
                        summary.increaseCount();
                        summary.addToTotal(value);
                    }
                    else
                    {
                        Summary initialSummary = new Summary();
                        initialSummary.setCount(1);
                        initialSummary.setTotal(value);
                        result.put(currentRow, initialSummary);
                    }
                    return true;
                }
            });
    
            for (Map.Entry<Animal, Summary> entry : result.entrySet())
            {
                Animal animal = entry.getKey();
                Summary summary = entry.getValue();
                System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
            }
        }
    
        final static class Animal
        {
            String date;
    
            String name;
    
            public Animal(final String date, final String n)
            {
                this.date = date;
                this.name = n;
            }
    
            @Override
            public int hashCode()
            {
                final int prime = 31;
                int result = 1;
                result = prime * result + ((date == null) ? 0 : date.hashCode());
                result = prime * result + ((name == null) ? 0 : name.hashCode());
                return result;
            }
    
            @Override
            public boolean equals(Object obj)
            {
                if (this == obj)
                {
                    return true;
                }
                if (obj == null)
                {
                    return false;
                }
                if (!(obj instanceof Animal))
                {
                    return false;
                }
                Animal other = (Animal) obj;
                if (date == null)
                {
                    if (other.date != null)
                    {
                        return false;
                    }
                }
                else if (!date.equals(other.date))
                {
                    return false;
                }
                if (name == null)
                {
                    if (other.name != null)
                    {
                        return false;
                    }
                }
                else if (!name.equals(other.name))
                {
                    return false;
                }
                return true;
            }
    
        }
    
        final static class Summary
        {
            private int total;
    
            private int count;
    
            void setTotal(int value)
            {
                total = value;
            }
    
            void setCount(int i)
            {
                count = i;
            }
    
            void increaseCount()
            {
                count++;
            }
    
            void addToTotal(int valueToAdd)
            {
                total += valueToAdd;
            }
        }
    }
    

    这篇关于使用java&amp;读取行maped过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆