如何使用java if else从JSON文件中删除重复的元素?

如何使用java if else从JSON文件中删除重复的元素?,java,json,duplicates,if-statement,Java,Json,Duplicates,If Statement,在我的代码中找到的start来自我的JSON文件。现在在我的JSON文件中,我有很多同名的“开始”。例如,在这个JSON文件中,我在开头有重复的内容(两个内容都是“audi”): 这是我的Java代码: String start = (String) jsonObject.get("start"); StartVertex startV = new StartVertex(start); helloGraphDB.addVertex(startV); 我不想让它添加相同“奥迪”

在我的代码中找到的start来自我的JSON文件。现在在我的JSON文件中,我有很多同名的“开始”。例如,在这个JSON文件中,我在开头有重复的内容(两个内容都是“audi”):

这是我的Java代码:

String start = (String) jsonObject.get("start");  
StartVertex startV = new StartVertex(start);  
helloGraphDB.addVertex(startV);    
我不想让它添加相同“奥迪”的2倍,否则我怎么写逻辑


谢谢。

`您可以使用arraylist检查值是否已插入到addVertex

比如: ArrayList addedVertex\u Val=新建ArrayList()

stringstart=(String)jsonObject.get(“start”);
布尔值shouldInsert=true;
对于(int al_length=0;al_length

`

您也可以使用HashMap而不是数组列表

这将比线性检查ArrayList更有效

您只需检查HashMap中是否有开始(如“audi”),如果没有,您可以将其添加到图形和HashMap中,如果HashMap中已经有开始,您可以跳过将其添加到图形和HashMap中

Does map contains 'audi' for start:false
Adding to graph
Does map contains 'audi' for start:true
Does map contains 'audi' for start:true
package com.infinitegraph.samples.hellograph;
//导入所有InfiniteGraph包
导入java.io.BufferedReader;
导入java.io.FileReader;
导入java.io.IOException;
导入com.infinitegraph.*;
导入org.json.simple.JSONObject;
导入org.json.simple.parser.JSONParser;
导入org.json.simple.parser.ParseException;
//导入SLF4J日志记录包
导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
导入com.infinitegraph.BaseVertex;
导入java.util.HashMap;
公共类HelloGraph
{
公共静态void main(字符串[]args)
{
BufferedReader br=null;
JSONParser=新的JSONParser();
//为HelloGraph类设置日志记录
Logger Logger=LoggerFactory.getLogger(HelloGraph.class);
//创建空事务,空图形数据库实例
事务tx=null;
GraphDatabase helloGraphDB=null;
//图形数据库和属性文件的名称
字符串graphDbName=“HelloGraph”;
字符串属性filename=“HelloGraph.properties”;
尝试
{
尝试
{
//删除已存在的图形数据库
delete(graphDbName,propertiesFileName);
}
捕获(存储异常)
{
logger.info(sE.getMessage());
}
//提示:添加代码以创建图形数据库及其内容
//创建图形数据库
logger.info(“>创建图形数据库…”);
create(graphDbName,propertiesFileName);
//开放图形数据库
logger.info(“>打开图形数据库…”);
helloGraphDB=GraphFactory.open(graphDbName,propertiesFileName);
//开始交易
logger.info(“>开始读/写事务…”);
tx=helloGraphDB.beginTransaction(AccessMode.READ\u WRITE);
//创建头部顶点
HeadServerTex head=新的HeadServerTex(“JSON文件”);
helloGraphDB.addVertex(头部);
试一试{
弦电流线;
br=新的BufferedReader(新的文件阅读器(“C:/Users/ji/Desktop/example3.json”);
HashMap=newhashmap();
而((sCurrentLine=br.readLine())!=null){
对象对象对象;
试一试{
obj=parser.parse(sCurrentLine);
JSONObject JSONObject=(JSONObject)对象;
//创建顶点的代码
logger.info(“>创建起始顶点…”);
String start=(String)jsonObject.get(“start”);
StartVertex startV=新的StartVertex(开始);
如果(!map.containsKey(开始))
{
地图放置(开始,1);
helloGraphDB.addVertex(startV);
}
//系统输出打印项次(结束);
String end=(String)jsonObject.get(“end”);
EndVertex endV=新的EndVertex(结束);
helloGraphDB.addVertex(endV);
stringrel=(String)jsonObject.get(“rel”);
//系统输出打印项次(rel);
logger.info(“>创建关系边缘…”);
relationship1=新关系(“”);
关系2=新关系(rel);
//连接边
logger.info(“>连接顶点…”);
startV.addEdge(relationship1,head,EdgeKind.directional,(short)0);
endV.addEdge(relationship2,startV,EdgeKind.directional,(short)0);
}捕获(解析异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
如果(br!=null)br.close();
}捕获(IOEX异常){
例如printStackTrace();
}
}
//指定用于遍历的命名根
info(“>命名根顶点…”);
helloGraphDB.nameVertex(“JSON Fi
ArrayList addedVertex_Val = new ArrayList();

    String start = (String) jsonObject.get("start");
    boolean shouldInsert = true;

    for (int al_length = 0; al_length < addedVertex_val.size(); al_length++) {
        String val = addedVertex_val.get(al_length).toString();
        if (val.equals(start)) {
            shouldInsert = false;
            break;
        }
    }

    if (shouldInsert) {
        StartVertex startV = new StartVertex(start);
        helloGraphDB.addVertex(startV);
        addedVertex_Val.add(startV);
    }
String a = "{\"rel\": \"AtLocation\", \"weight\": 0.5, \"dataset\": \"/d/dbpedia/en\", \"sources\": [\"/s/dbpedia/3.7\"], \"id\": \"0209765bf7185615ef242513f61ca0f61efe2a04\", \"features\": [\"audi AtLocation -\", \"audi - curitiba\", \"- AtLocation curitiba\"], \"end\": \"curitiba\", \"license\": \"/l/CC/By-SA\", \"uri\": \"/a/[AtLocation/,audi/,curitiba/]\", \"start\": \"audi\", \"context\": \"/ctx/all\", \"surfaceText\": null}";
        String b = "{\"rel\": \"AtLocation\", \"weight\": 0.5, \"dataset\": \"/d/dbpedia/en\", \"sources\": [\"/s/dbpedia/3.7\"], \"id\": \"5158d1cfce728efb3e42840d166ec06153a3d77d\", \"features\": [\"audi AtLocation -\", \"audi - ingolstadt\", \"- AtLocation ingolstadt\"], \"end\": \"unite_state\", \"license\": \"/l/CC/By-SA\", \"uri\": \"/a/[AtLocation/,audi/,ingolstadt/]\", \"start\": \"audi\", \"context\": \"/ctx/all\", \"surfaceText\": null}";
        JSONParser p = new JSONParser();
        JSONObject jsonA = (JSONObject) p.parse( a );
        JSONObject jsonB = (JSONObject) p.parse( b );
        HashMap<String, Integer> map = new HashMap<String, Integer>();

        String start = (String) jsonA.get( "start" );
        System.out.println( "Does map contains 'audi' for start:" + map.containsKey( start ) );
        if( !map.containsKey( start ) )
        {
            map.put( start, 1 );
            System.out.println( "Adding to graph" );
        }
        System.out.println( "Does map contains 'audi' for start:" + map.containsKey( start ) );

        start = (String) jsonB.get( "start" );
        if( !map.containsKey( start ) )
        {
            map.put( start, 2 );
            System.out.println( "Adding to graph" );
        }

        System.out.println( "Does map contains 'audi' for start:" + map.containsKey( start ) );
Does map contains 'audi' for start:false
Adding to graph
Does map contains 'audi' for start:true
Does map contains 'audi' for start:true
package com.infinitegraph.samples.hellograph;

// Import all InfiniteGraph packages
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.infinitegraph.*;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
// Import SLF4J logging packages
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.infinitegraph.BaseVertex;
import java.util.HashMap;

public class HelloGraph
{

    public static void main(String[] args)
    {
                BufferedReader br = null;
                JSONParser parser = new JSONParser();

        // Set up logging for the HelloGraph class
        Logger logger = LoggerFactory.getLogger(HelloGraph.class);

        // Create null transaction, null graph database instance
        Transaction tx = null;
        GraphDatabase helloGraphDB = null;

        // Name for graph database and property file
        String graphDbName = "HelloGraph";
        String propertiesFileName = "HelloGraph.properties";    

        try
        {
            try
            {
                // Delete graph database if it already exists
                GraphFactory.delete(graphDbName, propertiesFileName);
            }
            catch (StorageException sE)
            {
                logger.info(sE.getMessage());
            }

            // HINT: Add code to create graph database and its contents
            // Create graph database
            logger.info("> Creating graph database ...");
            GraphFactory.create(graphDbName, propertiesFileName);

            // Open graph database
            logger.info("> Opening graph database ...");
            helloGraphDB = GraphFactory.open(graphDbName, propertiesFileName);

            // Begin transaction
            logger.info("> Starting a read/write transaction ...");
            tx = helloGraphDB.beginTransaction(AccessMode.READ_WRITE);

            //create head vertex
            HeaderVertex head = new HeaderVertex("JSON File");
            helloGraphDB.addVertex(head);

            try {
                String sCurrentLine;

                br = new BufferedReader(new FileReader("C:/Users/ji/Desktop/example3.json"));

                HashMap<String, Integer> map = new HashMap <String, Integer>();

                while ((sCurrentLine = br.readLine()) != null) {

                    Object obj;

                    try {
                        obj = parser.parse(sCurrentLine);
                        JSONObject jsonObject = (JSONObject) obj;

                        //code to create vertex
                        logger.info("> Creating Start vertices ...");     
                        String start = (String) jsonObject.get("start");
                        StartVertex startV = new StartVertex(start);
                        if (!map.containsKey(start))
                        {
                            map.put(start,1);
                            helloGraphDB.addVertex(startV); 
                        }

                        //System.out.println(end);
                        String end = (String) jsonObject.get("end");
                        EndVertex endV = new EndVertex(end);
                        helloGraphDB.addVertex(endV);

                        String rel = (String) jsonObject.get("rel");
                        //System.out.println(rel);
                        logger.info("> Creating Relationship edge ...");
                        Relationship relationship1 = new Relationship("");
                        Relationship relationship2 = new Relationship(rel);

                        // Connect edges
                        logger.info("> Connecting vertices ...");
                        startV.addEdge(relationship1, head, EdgeKind.BIDIRECTIONAL, (short) 0);
                        endV.addEdge(relationship2, startV, EdgeKind.BIDIRECTIONAL, (short) 0);

                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            // Specify a named root for traversal
            logger.info("> Naming a root vertex ...");
            helloGraphDB.nameVertex("JSON File", head);

            // Commit to save your changes to the graph database
            logger.info("> Committing changes ...");
            tx.commit();
        }

        catch (ConfigurationException cE)
        {
            logger.warn("> Configuration Exception was thrown ... ");
            logger.error(cE.getMessage());
        }

        finally
        {
            // If the transaction was not committed, complete
            // will roll it back
            if (tx != null)
                tx.complete();
            if (helloGraphDB != null)
            {
                helloGraphDB.close();
                logger.info("> On Exit: Closed graph database");
            }
        }
    }

}

// HINT: Add class definitions for Person and Meeting classes here.
class HeaderVertex extends BaseVertex
{
    private String header;

    public HeaderVertex (String header)
    {
        setStartName(header);
    }

    public void setStartName (String header)
    {
        markModified();
        this.header = header;
    }

    public String toString()
    {
        fetch();
        return this.header;
    }
}

class StartVertex extends BaseVertex
{
    private String start;

    public StartVertex (String start)
    {
        setStartName(start);
    }

    public void setStartName (String start)
    {
        markModified();
        this.start = start;
    }

    public String toString()
    {
        fetch();
        return this.start;
    }
}

class EndVertex extends BaseVertex
{
    private String end;

    public EndVertex (String end)
    {
        setEndVertex(end);
    }

    public void setEndVertex (String end)
    {
        markModified();
        this.end = end;
    }

    public String toString()
    {
        fetch();
        return this.end;
    }
}

class Relationship extends BaseEdge
{
    private String rel;

    public Relationship (String rel)
    {
        setRelationship(rel);
    }

    public void setRelationship (String rel)
    {
        markModified();
        this.rel = rel;
    }

    public String toString()
    {
        fetch();
        return this.rel;
    }
}