How do I remove a map entry for the specified key-value?

Beginning from Java 8, the Map interface includes the remove(Object key, Object value) method, which removes the entry for the specified key only if it is currently mapped to the specified value.

Here is a Java 8 way of accomplishing this:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapRemoveKeyValueExample {
    public static void main(String[] args) {
        Map<String, String> myMap = new HashMap<>();

        myMap.put("key1", "value1");
        myMap.put("key2", "value2");

        System.out.println("Map before: " + myMap);

        myMap.remove("key1", "value1");

        System.out.println("Map after: " + myMap);
    }
}

Output:

Map before: {key1=value1, key2=value2}
Map after: {key2=value2}

It’s important to note, however, that this method will do nothing if the initially passed value does not match the value currently mapped by the key in the map. The method also returns a boolean indicating whether the removal was successful (i.e., the key/value pair was in the map).

The remove(Object key, Object value) method is indeed a more concise way to accomplish this task in Java 8 or above, as it does not require an explicit condition check as in the previous approach.

How do I delete entity object in JPA?

The following code example show you how to delete or remove entity object from database using JPA. The first class that we are going to create is ArtistDaoImpl which implements ArtistDao. This DAO class handles the delete process either by the entity ID or by the entity object itself. We define the delete process in deleteById(Long id) and delete(Artist artist) methods.

In those methods we call the EntityManager.remove() method. This method of EntityManager will take care of removing the entity object from our database. Let’s see the DAO code below:

package org.kodejava.jpa.dao;

import org.kodejava.jpa.entity.Artist;

import java.util.List;

public interface ArtistDao {
    Artist findById(Long id);

    void save(Artist artist);

    void update(Artist artist);

    List<Artist> getArtists();

    void deleteById(Long id);

    void delete(Artist artist);
}
package org.kodejava.jpa.dao.impl;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;

public class ArtistDaoImpl implements ArtistDao {
    private final EntityManager manager;

    public ArtistDaoImpl(EntityManager manager) {
        this.manager = manager;
    }

    /**
     * Find Artist based on the entity id.
     *
     * @param artistId the artist id.
     * @return Artist.
     * @throws EntityNotFoundException when no artist is found.
     */
    public Artist findById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist == null) {
            throw new EntityNotFoundException("Can't find Artist for ID "
                    + artistId);
        }
        return artist;
    }

    @Override
    public void save(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    /**
     * Update Artist information.
     *
     * @param artist an Artist to be updated.
     */
    @Override
    public void update(Artist artist) {
        manager.getTransaction().begin();
        manager.merge(artist);
        manager.getTransaction().commit();
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public List<Artist> getArtists() {
        Query query = manager.createQuery("select a from Artist a", Artist.class);
        return query.getResultList();
    }

    /**
     * Delete artist by their id.
     *
     * @param id the artist id.
     */
    @Override
    public void deleteById(Long id) {
        Artist artist = manager.find(Artist.class, id);
        if (artist != null) {
            manager.getTransaction().begin();
            manager.remove(artist);
            manager.getTransaction().commit();
        }
    }

    /**
     * Delete artist entity.
     *
     * @param artist the object to be deleted.
     */
    @Override
    public void delete(Artist artist) {
        manager.getTransaction().begin();
        manager.remove(artist);
        manager.getTransaction().commit();
    }
}

After defining the delete methods in the ArtistDao class we create a simple program to demonstrate both of them. In this program we start by create the EntityManagerFactory object from the defined persistence unit in the persistence.xml file. Then we create the EntityManager object, and we pass it to our ArtistDaoImpl object. And then we call the delete methods to remove entity from the database.

To show you the result of the delete process we print out the artist data before and after the delete method is called.

package org.kodejava.jpa;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.dao.impl.ArtistDaoImpl;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class EntityRemoveDemo {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
                Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager manager = factory.createEntityManager();

        ArtistDao dao = new ArtistDaoImpl(manager);
        System.out.println("Before Delete:");
        printArtists(dao.getArtists());

        // Remove artist with ID = 1.
        dao.deleteById(1L);

        // Remove artist with ID = 2.
        Artist artist = dao.findById(2L);
        dao.delete(artist);

        System.out.println("After Delete:");
        printArtists(dao.getArtists());
    }

    private static void printArtists(List<Artist> artists) {
        for (Artist artist : artists) {
            System.out.println("Artist = " + artist);
        }
    }
}

Here is the result of our code snippet. It shows the number of records before and after the delete process.

Before Delete:
Artist = Artist{id=1, name='Bon Jovi'}
Artist = Artist{id=2, name='Mr. Big'}
Artist = Artist{id=3, name='Metallica'}
After Delete:
Artist = Artist{id=3, name='Metallica'}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I remove tabs from JTabbedPane?

To remove tabs from JTabbedPane we can use the following remove methods:

  • remove(int index) method to remove a tab at the specified index.
  • remove(Component component) method to remove a tab that has the specified child component.
  • removeAll() method to remove all tabs.
package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class TabbedPaneRemoveTab extends JPanel {
    public TabbedPaneRemoveTab() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TabbedPaneRemoveTab();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTabbedPane Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TabbedPaneRemoveTab::showFrame);
    }

    private void initializeUI() {
        final JTabbedPane pane = new JTabbedPane(JTabbedPane.LEFT);
        pane.addTab("A Tab", new JPanel());
        pane.addTab("B Tab", new JPanel());

        JPanel tabPanel = new JPanel();
        pane.addTab("C Tab", tabPanel);
        pane.addTab("D Tab", new JPanel());
        pane.addTab("E Tab", new JPanel());

        // Remove the last tab from JTabbedPane
        pane.remove(pane.getTabCount() - 1);

        // Remove tab that contains a tabPanel component which is
        // the C Tab.
        pane.remove(tabPanel);

        JButton button = new JButton("Remove All Tabs");
        button.addActionListener(e -> {
            // Remove all tabs from JTabbedPane
            pane.removeAll();
        });

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));
        this.add(pane, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
    }
}

The output of the code snippet above is:

Remove Tabs from JTabbedPane